Firebase cloud messaging(FCM) 是什麼?

FCM 是一個跨平台的訊息傳送機制,提供可靠且免費傳遞訊息的功能。

如何使用 FCM?

在已經建立 Firebase 專案的情況下,啟動並使用 FCM 的過程非常簡單。

Android App 只需要加入一個 Service,Firebase 後臺只需要啟動 FCM 並建立要傳送的訊息,最後透過 Firebase 後台發送訊息,Android App 便可收到該訊息。

以下分為 Android App 端,以及 Firebase 後台端來說明。

首先是 Android App 端。

先加入 FCM 的依賴,在 Module 的 build.gradle 加入以下內容

implementation 'com.google.firebase:firebase-messaging:20.0.0'

接著在 AndroidManifest.xml 宣告 Service 如下,Service 名稱可以自訂,注意 <intent-filter> 的 <action> 的 android:name 的內容為 com.google.firebase.MESSAGING_EVENT

<service
android:enabled="true"
android:exported="true"
android:name=".notification.FirebaseMessagingReceiveService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>

接著來實作 Service,如下

package com.codefoxx.firebasedemo1app.notification
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
class FirebaseMessagingReceiveService : FirebaseMessagingService() {
    private val TAG = this::class.java.simpleName
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        Log.d(TAG, "receive notification:" + remoteMessage.notification?.body)
    }
    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.d(TAG, "onNewToken: " + token)
    }
}

Android App端設定完成!! 這樣便可收到訊息。

接下來是 Firebase 後台端

請先進入 Firebase 專案,進入專案之後如果是第一次使用 FCM 必須先建立網路推播憑證。步驟如下

1.點擊 Settings -> 專案設定
(Firebase 專案頁面左上方有 Project Overview,Project Overview 旁邊有一個齒輪圖示,該圖示就是 Settings)

2.點擊雲端通訊

3.在雲端通訊最下方有網路設定,其中有網路推播憑證,在該區塊中若沒有任何內容,請新增一組金鑰。

接下來就可以建立要發送訊息的內容了。

首先點擊畫面左側欄的 Cloud Messaging,再點擊新增通知就會進入訊息內容設定。

1.通知: 填寫訊息的Title和內容

2.指定目標: 選擇使用者區隔或主題
使用者區隔就是選擇符合的條件,其中的應用程式選擇發送目標 App 的 package name,代表所有安裝該目標 App 的裝置都會收到訊息。可以再點擊後方的且,選擇其他的條件。

主題是一個關鍵字,在 App 中必須先訂閱該主題才會發送到目標裝置。

3.排定時間: 就是發送訊息的時間,預設為現在,若有需求可以選擇其他項目。

以上為必選的訊息設定,以下的設定轉換事件和其他選項為選用,視需求來決定要不要使用。

完成後點擊審查會出現訊息提示內容,再按下發布就會發送訊息了。