我正在尝试从broadcastReceiver类观察MutableLiveData,但是它不起作用。
我发送了一条通知,并在其上添加了一个操作,该操作启动了未决的Intent。 endingIntent将广播发送到我的NotificationReceiver类,该类扩展了BroadcastReceiver。它进入onReceive函数,并更改MutableLiveData。 在另一个类中,我尝试观察此MutableLiveData,但它仅在初始化部分中第一次起作用。但是,当在NotificationReceiver的“ onRecieve”函数中更改MutableLiveData时,该观察器将无法正常工作。
通过操作创建通知
getRegionalCustomer
我的NotificationReceiver类:
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = "ZOOM"
}
val pendingIntent: PendingIntent =
PendingIntent.getBroadcast(context, 0, intent, 0)
val notifyBuilder = NotificationCompat.Builder(context, Constants.PRIMARY_CHANNEL_ID)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setSmallIcon(notificationIcon)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.addAction(
R.drawable.icon,
"zoom",
pendingIntent
)
mNotifyManager?.notify(notificationID, notifyBuilder.build())
观察片段:
class NotificationReceiver: BroadcastReceiver() {
var shouldZoom = MutableLiveData<Boolean>()
init {
shouldZoom.value = false
}
override fun onReceive(context: Context?, intent: Intent?) {
when (intent?.action) {
"ZOOM" -> zoomLoaction()
}
}
private fun zoomLoaction() {
shouldZoom.value = true
}
}
清单:
var notificationReceiver = NotificationReceiver()
notificationReceiver.shouldZoom.observe(this, Observer {
if (it) {
// Log
}
})