gpt4 book ai didi

android - Broadcast Receiver 只接收一次信息

转载 作者:行者123 更新时间:2023-11-29 23:48:01 25 4
gpt4 key购买 nike

我有一个同时发送两个广播的服务。

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的 Action 是一样的,只是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)
}
}
}

我观察到这些事件的 fragment :

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 在主线程上执行第一个 onReceivepostValue 任务之前被调用,因此值设置为第二个时间被忽略。您还可以从 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,因为它会立即设置值并从主线程调用。

关于android - Broadcast Receiver 只接收一次信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51170919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com