iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 26
0
Mobile Development

老姐好像要用 Kotlin 寫專案,能撐30天嗎?系列 第 26

合作愉快的第二十六天:聊天室功能調整和 FCM 推播(下)

今天一定要挽回一些顏面。「姐,我昨天忘了告訴妳,妳用的是 kotlin ,所以最好換成這兩個 Library 唷。」

  implementation 'com.google.firebase:firebase-messaging-ktx:20.3.0'
  implementation 'com.google.firebase:firebase-analytics-ktx:17.5.0'

「噢,對,不小心複製到 Java 的 Library 了,我馬上改,還有別的嗎?」老姐相當有敬業精神的發問。

「關於昨天妳問的 registration token 要傳到哪。我確認過 Firebase Cloud Messaging 提供兩種多裝置推播訊息,其中有一個 Topic messaging 模式,訂閱方式相對簡單。我規劃的流程是 App 先用 API 告訴 Server 要訂閱哪個題目, Server 訂閱成功後回傳給 App 對應的 FCM Topic Name ,這樣 Server 就不用經手 FCM registration token 。」

我迅速的下載 Firebase console 私鑰。

https://ithelp.ithome.com.tw/upload/images/20201005/2012919707VxdYD7tJ.png

build.gradle 加上 Firebase Admin sdk 。

    implementation 'com.google.firebase:firebase-admin:7.0.0'

Application.module 裡加上私鑰程式碼。

val serviceAccount = FileInputStream("${serviceAccount}.json")

    val options = FirebaseOptions.builder()
        .setCredentials(GoogleCredentials.fromStream(serviceAccount))
        .setDatabaseUrl("https://${firebaseProjectId}.firebaseio.com")
        .build()

    FirebaseApp.initializeApp(options)

存聊天資料的地方加上推播通知。

                        chat?.let {
                            val topic = "topic/${it.topic.id.value}"

                            val message: Message = Message.builder()
                                .setNotification(
                                    Notification.builder()
                                    .setTitle("FCM Message")
                                    .setBody("${it.message}")
                                    .build())
                                .putData("topicId", it.id.value.toString())
                                .setTopic(topic)
                                .build()

                            FirebaseMessaging.getInstance().send(message)
                        }

「我這邊也好了。」老姐有官網範例,程式改起來自然快。

https://github.com/firebase/quickstart-android/blob/d20b5b4a7e226ff49bef2c20fe0cc01ff23b171a/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/kotlin/MyFirebaseMessagingService.kt
https://ithelp.ithome.com.tw/upload/images/20201005/20129197mdlIuWmtCO.png

onMessageReceived 方法裡多加上:

        remoteMessage.notification?.let {
            sendNotification("Message Notification Body: ${it.body}")
        }

在取得 fcmTopicId 的 API 回傳後立即訂閱。

        FirebaseMessaging.getInstance().subscribeToTopic(fcmTopicName)
            .addOnCompleteListener { task ->
                var msg = "subscribed"
                if (!task.isSuccessful) {
                    msg = getString(R.string.msg_subscribe_failed)
                }
                Log.d("subscribeToTopic", msg)
            }

如今,我們等待的神聖時刻到了!手機成功顯示我們送的推播通知「世界正關注著你!」

https://ithelp.ithome.com.tw/upload/images/20201005/20129197KANR2cloJN.png

我倆邊說邊興奮地擊掌。「合作愉快!」「合作愉快!」

本次鐵人賽的作品在放進更多內容後已經成書,書名是《老姐要用Kotlin寫專案:從 Server 到 Android APP 的開發生存日記》,歡迎購買唷。https://www.tenlong.com.tw/products/9789864348978


上一篇
專業超車的第二十五天:聊天室功能調整和 FCM 推播(上)
下一篇
頭暈目眩的第二十七天:google 開發者帳戶
系列文
老姐好像要用 Kotlin 寫專案,能撐30天嗎?30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言