Exoplayer notification not clearing

Viewed 767

I have exoplayer integrated within my application based on this link.

I have added a pending intent inside createCurrentContentIntent().

    return PendingIntent.getActivity(
        context, 0,
        Intent(context, MyActivity::class.java), 0
    )

I face an issue over here. I started playing the audio and the player notification also comes up in the status bar. My requirement is to play audio even if the app is in the background. So, I haven't released the player in onStop(). I have added the below code in onDestroy().

    override fun onDestroy() {
        playerNotificationManager?.setPlayer(null)
        player?.stop()
        player?.release()
        player = null
        super.onDestroy()
    }

If I manually kill the application from the background when the player is playing, the notification doesn't go off. So, if I click on the notification it will crash with NullPointerException because MyActivtity is no more.

Could someone suggest a solution for the same?

2 Answers

I've implemented ExoPlayer along with MediaSessionCompat and MediaSessionConnector, which allows Exo to manage the media notification (and stuff like audio focus) implicitly.

class MyServiceClass {

    private lateinit var player: SimpleExoPlayer
    private lateinit var playerNotificationManager: PlayerNotificationManager
    private lateinit var mediaSession: MediaSessionCompat
    private lateinit var mediaSessionConnector: MediaSessionConnector

    override fun onCreate() {
        super.onCreate()

        player = ...
        playerNotificationManager = ...
        mediaSession = MediaSessionCompat(this, CONSTANT).apply{ ..setup callback... }
        mediaSessionConnector = MediaSessionConnector(mediaSession)
        mediaSessionConnector.setPlayer(player)
        playerNotificationManager.setMediaSessionToken(mediaSession.token)
        playerNotificationManager.setPlayer(player)

    }

    override fun onDestroy() {

        mediaSession.isActive = false
        mediaSession.release()
        mediaSessionConnector.setPlayer(null)
        playerNotificationManager.setPlayer(null)
        player.release()

        super.onDestroy()
    }
}

This should handle removing the notification, when you kill the app.

I also use a PlayerNotificationReceiver to react to notification changes by the system which is omitted in the code above. Also the whole part of triggering and reacting to notifications in the app is omitted.

I changed the complete implementation and used services. This solved the issue.

Related