3

I am facing a very strange issue while using exoplayer's PlayerNotificationManager for showing player notification. I am using following code for showing notification in foreground:

class AudioPlayerService : LifecycleService() {
    private val notificationListener = object : PlayerNotificationManager.NotificationListener {
        override fun onNotificationPosted(
            notificationId: Int,
            notification: Notification,
            ongoing: Boolean
        ) {
            super.onNotificationPosted(notificationId, notification, ongoing)
            if (ongoing)
                startForeground(notificationId, notification)
            else
                stopForeground(false)
        }
    }

    override fun onCreate() {
        super.onCreate()
        playerNotificationManager = PlayerNotificationManager(
            this,
            CHANNEL_ID,
            NOTIFICATION_ID,
            descriptionAdapter,
            notificationListener
        ).apply {
            setFastForwardIncrementMs(0)
            setRewindIncrementMs(0)
            setUseNextAction(false)
            setUsePreviousAction(false)
            setUseStopAction(false)
            setUseChronometer(false)
        }
        //...
    }

    override fun onDestroy() {
        releasePlayer()
        super.onDestroy()
    }
    //...
}

It is working as expected when music is playing and app is killed (cleared form recent), notification persist and music keeps on playing.

But if pause the music and clear notification(which should be cleared as music is not playing), and then kill app, it shows non-dismissable notification (which should not be shown) with pause button but pause button does not work and audio is not playing either.

How can I prevent notification from showing when App is killed and player is in paused state?

ahsanali274
  • 471
  • 2
  • 14

1 Answers1

0

I was able to solve this issue by overriding onTaskRemoved in my service.

    override fun onTaskRemoved(rootIntent: Intent?) {
        super.onTaskRemoved(rootIntent)
        if (player.isPlaying == false)
            stopForeground(true)
    }

This function is called when user remove App Task. We can check here whether we need our service to keep running.

ahsanali274
  • 471
  • 2
  • 14