我就是这样发送广播的
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())但在接收端我无法接受意图。请指导我什么可能是错误
发布于 2022-01-04 09:55:33
通过requireContext().sendBroadcast(intent)发送的广播不是本地广播
您还需要使用LocalBroadcastManager进行发送。
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)发布于 2022-01-04 05:53:52
登记接管人如下:
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>https://stackoverflow.com/questions/70574244
复制相似问题