Android 如何向MainActivity发送FCM消息

Android 如何向MainActivity发送FCM消息,android,kotlin,push-notification,firebase-cloud-messaging,Android,Kotlin,Push Notification,Firebase Cloud Messaging,我想在我的mainActivity中显示FCM接收到的消息作为导航徽章, 但如何从服务向活动发送数据? 我用过: 但是这段代码打开了新的MainActivity,同时还有另一个MainActivity 如果您的服务和活动在同一进程中运行,您可以尝试发送LocalBroadcast // Inside the service override fun onMessageReceived(p0: RemoteMessage) { super.onMessageReceived(p0)

我想在我的mainActivity中显示FCM接收到的消息作为导航徽章, 但如何从服务向活动发送数据? 我用过:


但是这段代码打开了新的MainActivity,同时还有另一个MainActivity

如果您的服务和活动在同一进程中运行,您可以尝试发送
LocalBroadcast

// Inside the service
override fun onMessageReceived(p0: RemoteMessage) {
    super.onMessageReceived(p0)
    val lbm = LocalBroadcastManager.getInstance(this)
    val dataIntent = Intent().apply { 
        putExtra("badge", p0.notification?.body) 
    }
    lbm.sendBroadcast(dataIntent)
}

// Inside the service
override fun onMessageReceived(p0: RemoteMessage) {
    super.onMessageReceived(p0)
    val lbm = LocalBroadcastManager.getInstance(this)
    val dataIntent = Intent().apply { 
        putExtra("badge", p0.notification?.body) 
    }
    lbm.sendBroadcast(dataIntent)
}

// Inside the activity
private val lbm by lazy { LocalBroadcastManager.getInstance(this) }
private val badgeListener = object : BroadcastReceiver() {
    override fun onReceive(ctx: Context, data: Intent) {        
         val count = intent.getIntExtra("badge")
         // Update the view here
    }
}


override fun onCreate(){
    // Other stuff
    lbm.registerReceiver(badgeListener)
}

override fun onDestroy() {
    lbm.unregisterReceiver(badgeListener)
}