android - Broadcast Receiver 只接收一次信息
问题描述
我有一个同时发送两个广播的服务。
val i = Intent(PlayerService.INTENT_ACTION)
i.putExtra(EVENT_EXTRAS, PlayerEvent.PLAYER_READY.ordinal)
i.putExtra(DURATION_EXTRAS, mp.duration) //some duration
sendBroadcast(i)
val i1 = Intent(PlayerService.INTENT_ACTION)
i1.putExtra(EVENT_EXTRAS, PlayerEvent.ON_SECOND_CHANGED.ordinal)
i1.putExtra(DURATION_EXTRAS, player.duration) //another duration
sendBroadcast(i1)
Intents的作用是一样的,但是extras是不同的。最后,我只能从第二次广播中得到答案。谁知道是什么原因?
我的接收器实时数据:
class PlayerLiveEvent(val context: Context) : LiveData<Intent>() {
override fun onActive() {
super.onActive()
context.registerReceiver(receiver, IntentFilter(PlayerService.INTENT_ACTION))
}
override fun onInactive() {
super.onInactive()
context.unregisterReceiver(receiver)
}
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
postValue(intent)
}
}
}
我观察到这些事件的片段:
PlayerLiveEvent(activity!!).observe(this, Observer {
it?.apply {
val event = PlayerEvent.values()[getIntExtra(EVENT_EXTRAS, 0)]
when (event) {
PlayerEvent.PLAYER_READY -> {
println("PLAYER_READY")
}
PlayerEvent.ON_SECOND_CHANGED -> {
println("ON_SECOND_CHANGED")
}
else -> println()
}
}
})
解决方案
在主线程上执行第一个任务onReceive
之前调用您的第二个,因此第二次设置的值被忽略。您还可以从以下实现中看到这一点:postValue
onReceive
postValue
...
synchronized (mDataLock) {
// for your second call this will be false as there's a pending value
postTask = mPendingData == NOT_SET;
mPendingData = value;
}
// so this is true and so the method returns prematurely
if (!postTask) {
return;
}
...
其中,使用setValue
它是因为它立即设置值并从主线程调用。
推荐阅读
- javascript - 如何按值对对象数组进行排序?
- python - 如何在 Django 中结合过滤和分页?
- c# - 为什么 MSBuild 有时会忽略 TargetFrameworkVersion?
- ansible - ansible - 无法访问嵌套列表中的项目
- python - 如何用百分比编写一个计算公式来用python构建一个金融计算器?
- java - Maven多模块依赖解析
- css - mat-tab-group 宽度对 flex 中的宽度 100% 容器没有反应
- azure-active-directory - Azure B2C 启用诊断日志以与请求订阅的日志分析集成,即使租户已经喜欢订阅
- javascript - 如何将属性添加到数组中的对象?
- python - 我有什么方法可以使此代码与 elif 中的嵌套 if 一起使用?