运用Firebase Admin SDK发送Notification

前言

发送FCM推播有以下几种方式:

在Firebase Console send test messeage直接对https://fcm.googleapis.com/fcm/send 发送post request运用Firebase Admin SDK发送Notification

今天我们主要来介绍第三种方式的运用。


环境介绍

开发电脑:MAC
开发工具:Eclipse
测试工具:GCM Notifications(Chrome Plugin)


下载与安装

Step 1.因为我们主要是介绍如何运用Firebase Admin SDK发送Notification,所以我们可以先下载Google写好的GCM Notifications接收推播,取代Android实作的部分。首先可以到GCM Notifications的GitHub点选下载压缩档。
http://img2.58codes.com/2024/20114725lmqIvuJZUF.png

Step 2.接着在Chrome的扩充功能载入未封装项目,并选取刚刚下载下来的压缩档里面的一个範例资料夹(\chrome-app-samples-master\samples\gcm-notifications)。
http://img2.58codes.com/2024/20114725DwAO969Sbp.png


建立Firebase专案

Step 1.接着我们到Firebase Console,并新增专案。
http://img2.58codes.com/2024/20114725fNZWizhm7l.png

Step 2.新增后点选左上角的齿轮,并进入专案设定,可以看到我们的专案已经产生了伺服器金钥。
http://img2.58codes.com/2024/20114725Ex86K2pznX.png

Step 4.可以看到我们专案的伺服器金钥以及寄件者ID(Sender ID)。
http://img2.58codes.com/2024/20114725ETXL5OP7Bo.png

Step 5.我们把寄件者ID贴到刚刚装的GCM Notifications Chrome Plugin,并点选「Register」,便产生我们等等推播需要的Push Token。
http://img2.58codes.com/2024/20114725bB4L94H5EA.png

Step 6.接着点选服务帐户的tab,并将程式码片段设定为Java,并点选产生新的私密金钥,便会下载金钥的json档,我们等等将会在专案中引入这个金钥json档来发送推播。
http://img2.58codes.com/2024/20114725e2f8cgdRwF.png


运用Firebase Admin SDK发送Notification

Step 1.我们在程式中放上刚刚下载的刚刚下载的金钥json档路径,

FileInputStream serviceAccount = null;try {    serviceAccount = new FileInputStream("刚刚下载的金钥json档路径");} catch (FileNotFoundException e) {    e.printStackTrace();}FirebaseOptions options = null;try {    options = new FirebaseOptions.Builder()        .setCredentials(GoogleCredentials.fromStream(serviceAccount))        .setDatabaseUrl("https://<Datebase.Domain>.firebaseio.com")        .build();} catch (IOException e) {    e.printStackTrace();}FirebaseApp.initializeApp(options);String registrationToken = "你要推播装置的push token";Message message = Message.builder()    .putData("title", "运用Firebase Admin SDK发送Notification")    .putData("author", "Greg")    .setToken(registrationToken)    .build();String response = null;try {    response = FirebaseMessaging.getInstance().send(message);} catch (FirebaseMessagingException e) {    e.printStackTrace();}System.out.println("Successfully sent message: " + response);

Step 2.我们就可以看到浏览器跳出了收到推播的通知,而内容便是我们在程式中putData的资料。
http://img2.58codes.com/2024/20114725jfYlYGZL8K.png


结论

这次的练习是在我们已经知道我们要推播装置的push token,并且直接在我们的程式中推播到指定的装置,但如果在实务上要这样一个一个装置推播的话想必是很不方便,所以Firebase也还有提供其他不同的推播方式,像是我们可以推播给所有下载这个App的使用者,或是我们也可以设定主题(Topic),并且只推播给有订阅这个主题的使用者,


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章