首页 > 解决方案 > 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()
            }
        }
    })

标签: androidkotlin

解决方案


在主线程上执行第一个任务onReceive之前调用您的第二个,因此第二次设置的值被忽略。您还可以从以下实现中看到这一点:postValueonReceivepostValue

    ...
    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它是因为它立即设置值并从主线程调用。


推荐阅读