Home > OS >  Local Broadcast is not receiving broadcast
Local Broadcast is not receiving broadcast

Time:01-05

This is how I'm sending 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)
            }

And this is how I'm receiving Broadcast

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)
                }

This is how I'm registering it in on create of service

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

but at receiving end I'm unable to receive intent. Kindly guide me what could be possible error

CodePudding user response:

Broadcasts sent via requireContext().sendBroadcast(intent) are not local broadcasts

You need to use LocalBroadcastManager for the sending as well.

LocalBroadcastManager.getInstance(this).sendBroadcast(intent)

CodePudding user response:

register receiver like this:

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

or this: add the filter to your receiver, in AndroidManifest.xml

<intent-filter>
    <action android:name="PAUSE" />
</intent-filter>
<intent-filter>
    <action android:name="PLAY" />
</intent-filter>
  •  Tags:  
  • Related