本地广播收不到广播

Local Broadcast is not receiving broadcast

这就是我发送广播的方式

if (isPlaying) {
                val intent = Intent(MUSIC_REQUEST)
                intent.action = PAUSE
                requireContext().sendBroadcast(intent)
                binding.playSong.setImageResource(R.drawable.ic_play_icn)
            } else {
                val intent = Intent(MUSIC_REQUEST)
                intent.action = PLAY
                requireContext().sendBroadcast(intent)
                binding.playSong.setImageResource(R.drawable.ic_pause_icn)
            }

这就是我接收广播的方式

when (intent!!.action) {
                PAUSE -> {
                    if (mediaPlayer!!.isPlaying) {
                        Log.i(TAG, "onReceive: paused Received")
                        mediaPlayer!!.pause()
                        isPlaying = false
                        val pI = Intent(MUSIC_REQUEST)
                        pI.action = PAUSE_REQUEST_COMPLETED
                        sendBroadcast(pI)

                    }
                }
                PLAY -> {
                    isPlaying = true
                    Log.i(TAG, "onReceive: play Received")
                    mediaPlayer!!.start()
                    val pI = Intent(MUSIC_REQUEST)
                    pI.action = PLAY_REQUEST_COMPLETED
                    sendBroadcast(pI)
                }

这就是我在创建服务时注册它的方式

LocalBroadcastManager.getInstance(this).registerReceiver(receiver, IntentFilter())

但在接收端我无法接收到意图。请指导我可能出现的错误

像这样注册接收器:

val intentFilter = IntentFilter()
filter.addAction(PAUSE)
filter.addAction(PLAY)
context.registerReceiver(receiver, intentFilter)

或者这个: 在 AndroidManifest.xml

中将过滤器添加到您的接收器
<intent-filter>
    <action android:name="PAUSE" />
</intent-filter>
<intent-filter>
    <action android:name="PLAY" />
</intent-filter>

通过requireContext().sendBroadcast(intent)发送的广播不是本地广播

您也需要使用 LocalBroadcastManager 发送。

LocalBroadcastManager.getInstance(this).sendBroadcast(intent)