Firebase

📢【Firebase】Android Firebase Cloud Messaging 雲端推播 FCM 範例🔥

📢【Firebase】Android Firebase Cloud Messaging 雲端推播 FCM 範例🔥

Firebase Cloud Messaging (FCM) 是 Google 建立的跨平台消息技術,可以用於手機程式(iOS 和 Android)之間的交互。這項技術可以讓開發者達成一個目標:在手機程式上傳送和接收消息。它可以單向傳送(只針對終端用戶於指定時間接收指定消息)和雙向傳送(與終端用戶互相對話)兩種形式。


文章目錄

  1. FCM Firebase 與專案連結
  2. FCM SDK 與 google-services.json 導入進專案
  3. FCM 繼承 FirebaseMessagingService 並覆寫 onMessageReceived 方法
  4. FCM Manifest 增加權限與 Service
  5. FCM 取得使用者的 Token
  6. FCM Notification 與 Data
  7. FCM Postman 測試

1.FCM Firebase與專案連結

2.FCM SDK 與 google-services.json 導入進專案

3.繼承 FirebaseMessagingService 並覆寫 onMessageReceived 方法

class MyMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(remoteMessage: RemoteMessage) {

        //喚醒手機
        wakeUpPhone()

        //O以上需要添加channel
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel("msg", "消息", NotificationManager.IMPORTANCE_HIGH)
            notificationManager.createNotificationChannel(channel)
        }

        //點擊跳轉畫面
        val pendingIntent = PendingIntent.getActivity(this,
            0,
            Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP),
            PendingIntent.FLAG_IMMUTABLE)

        //通知欄
        val notification = NotificationCompat.Builder(this, "msg")
            .setContentTitle(remoteMessage.data["title"]) //Data收到
            .setContentText(remoteMessage.data["msg"]) //Data收到
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.icon)
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.icon))
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .build()

        notificationManager.notify(Random.nextInt(5), notification)
    }

    private fun wakeUpPhone() {
        val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
        powerManager.newWakeLock(
            PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
            "app:bright")
            .apply {
                //開啟螢幕(10分鐘)
                acquire(10 * 60 * 1000L)
                //釋放資源
                release()
            }
    }

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.e("onNewToken", token)
    }

}

4.Manifest 增加權限與 Service

<!-- 喚醒手機-->
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<!-- Android13以上-->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

<service android:name=".MyMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

5.取得使用者的 Token

FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
    if(task.isSuccessful) {
        Log.e("FCM Token", task.result)
    }
}

6.Notification 與 Data

App狀態         Notification               Data
前景            onMessageReceived          onMessageReceived
背景            調用系統本身                onMessageReceived

7.Postman 測試

https://fcm.googleapis.com/fcm/send

添加 Headers
server_key : 專案設定 > 雲端通訊

添加 Body (raw JSON)
notification
{
    "to": "device token",
    "notification": {
        "title": "標題",
        "body": "內容"
    }
}
data
{
    "to": "device token",
    "data": {
        "title": "標題",
        "body": "內容"
    }
}

發表迴響