初學者實現Firebase雲訊息傳遞(FCM)小筆記
在Android App 植入Firebase Cloud Messaging (FCM),過程不算複雜。只要跟隨Firebase的指引
A. 把下列這行加到build.gradle 的dependencies 內
compile 'com.google.firebase:firebase-messaging:11.8.0'
(com.google.firebase:firebase-messaging:xx.x.x 版本編號請參考更新資料)
如果有需要在收到Notification後截取Message進一步執行其他動作,才要修改以下其餘部分:
- B. 建立一個extends FirebaseMessagingService的service class
- C. 在manifest 檔案加入上述的service block和intent-filter
B. Extend FirebaseMessagingService class
因為收到的message會通過 onMessageReceived(RemoteMessage msg) ,所以我們要@Override 它並按需要自行在內加入method 。
onMessageReceived(){} 內的所有都不是必需,我只是為方便偵測收到的資訊。
C. manifest 加入
android:name=".ServiceFirebaseMessaging"> android:name="com.google.firebase.MESSAGING_EVENT"/>
ServiceFirebaseMessaging 其實就是之前我們extend出來的新class name,所以如果剛才你把新class 命名為 NewMsgService ,那麼你便應該把:
android:name=".ServiceFirebaseMessagingService"
改為:
android:name=".NewMsgService"
以Notifications composer (通知編輯器)測試接收訊息功能
在Notifications composer (通知編輯器)頁面發送訊息,觀察是否成功植入Messaging功能。
測試FCM 訊息功能要注意以下幾點
- 你只會在程式不在前台開啟時收到Notification;
- 以Notifications composer送出的Message必定包含notification payload資訊,所以...
- 如果你按照我以上的part B和C去做
- 開啟了App,訊息都會以Toast方式顯示出來;
- 沒有開啟App,只會收到Notification,而不會顯示到Toast
詳細可參考: https://firebase.google.com/docs/cloud-messaging/android/receive
以上都不是甚麼進階教學,不過若然對你有幫助,歡迎留言讓我知道 ^^