Search code examples
androidservicebroadcastreceiver

Broadcast receiver added inside onCreate() of foreground service not working


Broadcast receiver class inside the service

  inner class ServiceNotificationReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent!!.action
            Util.log("action from foreground services")
            when (action) {
                FOREGROUND_NEXT -> {
                    next()
                }
                FOREGROUND_PREVIOUS -> {
                    prevoius()
                }
                FOREGROUND_PLAY_PAUSE -> {
                    if (exoPlayer.isPlaying) {
                        pause()
                    } else {
                        play()
                    }
                }
                FOREGROUND_STOP -> {
                    stopSelf()
                }
            }
        }

    }

I am registering it inside the onCreate() of the service like so

  serviceNotificationListener = ServiceNotificationReceiver()

        val intentfliter = IntentFilter().apply {
            addAction(FOREGROUND_PLAY_PAUSE)
            addAction(FOREGROUND_PREVIOUS)
            addAction(FOREGROUND_NEXT)
            addAction(FOREGROUND_STOP)
        }
        this.registerReceiver(serviceNotificationListener, intentfliter)

The pending intent

playintent = Intent(this, ServiceNotificationReceiver::class.java).setAction(
        FOREGROUND_PLAY_PAUSE
    )

    playpendingIntent =
        PendingIntent.getBroadcast(this, 0, playintent, PendingIntent.FLAG_UPDATE_CURRENT)

I am adding it as an action inside the notification builder like so

  addAction(
                com.google.android.exoplayer2.R.drawable.exo_icon_previous,
                "Previous",
                previouspendingIntent
            )

However the clicks are not registering inside the service. I cannot add it in the manifest due to some complexity in the app and this is the only way. So what could be the issue. Is it the flags or something else.


Solution

  • You're setting your intent target component to yourpackage.YourService.ServiceNotificationReceiver which is not registered in manifest, system will not be able to resolve it and nothing is executed.

    Modify your intent to target only your apps package then your receiver will be able to match it:

    playintent = Intent().setPackage(this.packageName).setAction(FOREGROUND_PLAY_PAUSE)