iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 16
0
Software Development

Kotlin 30 天,通過每天一個小 demo 學習 Android 開發系列 第 16

Kotlin 開發第 16 天 PushMessaging (Firebase + BroadcastManager)

PushMessaging

這次通過 Firebase 對設備進行 Push Notification

  • 當設備收到 Push Notification 的時候,將內容通過 Alert 顯示出來。

Firebase

這是一家被 Google 收購的公司,提供多種 Serverless 的服務,這次打算通過 Firebase 來 push message 到設備上。

Firebase 已經被整合進 Android Studio 當中了,所以可以直接通過 Tools -> Firebase 來進行設定。
https://ithelp.ithome.com.tw/upload/images/20171219/20107329OaLJbZKfEh.png

Firebase -> Cloud Messaging -> Set up Firebase Cloud Messaging
https://ithelp.ithome.com.tw/upload/images/20171219/20107329UStLWJqFfB.png

通過 Connect to Firebase 建立一個應用,並取得設定檔 google-services.json
https://ithelp.ithome.com.tw/upload/images/20171219/20107329wzU0M5qQN1.png

通過 Add FCM to your app 會加載需要的 Plugin,當然也可以手動到 build.gradle 中引入
https://ithelp.ithome.com.tw/upload/images/20171219/20107329z1HXMXok0u.png


FirebaseMessagingService

我們通過建立一個繼承於 FirebaseService 的 service 並且 override onMessageReceived()

class MessageService : FirebaseMessagingService() {

    override fun onMessageReceived(message: RemoteMessage?) {
        super.onMessageReceived(message)

        Log.e("firebase message", message?.notification?.body)

    }

}

在 AndroidManifest.xml 中加入這個 Service

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

Firebase Notification

在 Firebase 的後台上發送消息。
https://ithelp.ithome.com.tw/upload/images/20171219/20107329Wgrh8NzeoF.png

推送後在 Android Studio 的 Run 中可以看到我們的 log

https://ithelp.ithome.com.tw/upload/images/20171219/20107329FkYMwjTJDG.png

當然也可以通過昨天提到的 NotificationManager 來顯示推送資訊。

    private fun sendNotification(message:String) {
        val notification = NotificationCompat.Builder(this,"channel id test")
                .setSmallIcon(R.drawable.icon_don_s)
                .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.icon_don))
                .setContentTitle("Notification from Firebase")
                .setContentText(message)
                .build()

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(1, notification)

    }

BroadcastManager

如果我們想要在收到 Push Notification 之後,在 Activity 上顯示 Alert message ,可以通過 LocalBoradcastManager

在 MessageService 中加入一個方法,用來通過 Intent 進行廣播。

其中 Intent 會指定 action 為 「DonMessage」之後 BroadcastReceiver 可以通過這個 action 來篩選出這條廣播。

    lateinit var broadcast:LocalBroadcastManager

    private fun showAlert(message:String) {
        val intent = Intent("DonMessage")
        intent.putExtra("message", message)
        broadcast.sendBroadcast(intent)
    }

然後我們在 MainActivity 定義一個 BroadcastReceiver

    private var messageReceiver = object:BroadcastReceiver(){

        override fun onReceive(p0: Context?, p1: Intent?) {
            val simpleAlert = AlertDialog.Builder(this@MainActivity).create()
            simpleAlert.setTitle("Alert")
            simpleAlert.setMessage("Show simple Alert")

            simpleAlert.setButton(AlertDialog.BUTTON_POSITIVE, "OK", {
                dialogInterface, i ->
                Toast.makeText(applicationContext, "You clicked on OK", Toast.LENGTH_SHORT).show()
            })

            simpleAlert.show()
        }

    }

MainAcitvity 在 onStart() 的時候註冊廣播監聽,通過 IntentFilter 來篩選廣播

    override fun onStart() {
        super.onStart()
        LocalBroadcastManager.getInstance(this).registerReceiver(messageReceiver, IntentFilter("DonMessage"))
    }

MainActivity 在 onStop() 的時候取消註冊廣播監聽

    override fun onStop() {
        super.onStop()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(messageReceiver)
    }

google-Services.json

這次開發過程中一開始不是很順利,收不到 Firebase 的 Push Messaging。

後來發現是 IDE 生成的 google-services.json 有錯,替換成 Firebase 網站上的 google-services.json 以後就沒問題了。


筆記

問題:Android 似乎不像 iOS 一定要通過官方的 Server 來對設備進行 Push Notification
之後可以在寫後端的時候進一步了解。


參考


上一篇
Kotlin 開發第 15 天 Notification( NotificationManager)
下一篇
Kotlin 開發第 17 天 PullToRequest ( SwipeRefreshLayout + CardLayout)
系列文
Kotlin 30 天,通過每天一個小 demo 學習 Android 開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言