如何向 MainActivity 发送 FCM 消息
how to send FCM message to MainActivity
我想在我的 mainActivity 中显示 FCM 收到的消息作为 bottomNavigation 徽章,
但是如何从服务向 activity 发送数据?
我用过:
override fun onMessageReceived(p0: RemoteMessage) {
super.onMessageReceived(p0)
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.putExtra("badge", p0.notification?.body)
startActivity(intent)
}
但是这段代码打开了一个新的 MainActivity,同时还有另一个 MainActivity!
如果您的服务和 activity 运行 在同一进程中,您可以尝试发送 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 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)
}
我想在我的 mainActivity 中显示 FCM 收到的消息作为 bottomNavigation 徽章, 但是如何从服务向 activity 发送数据? 我用过:
override fun onMessageReceived(p0: RemoteMessage) {
super.onMessageReceived(p0)
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.putExtra("badge", p0.notification?.body)
startActivity(intent)
}
但是这段代码打开了一个新的 MainActivity,同时还有另一个 MainActivity!
如果您的服务和 activity 运行 在同一进程中,您可以尝试发送 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 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)
}