Android Kotlin - ExoPlayer keeps playing when app goes to background

Viewed 253

So far I only found questions about how to make ExoPlayer keep playing when app goes to background. Why the hell is that the case by me without coding this bs??

This is what I have so far and it's inside RecyclerView OnBingViewHolder:

val player = ExoPlayer.Builder(context).build()
val mediaItem: MediaItem = MediaItem.fromUri(fileUrl)
player.setMediaItem(mediaItem)
player.repeatMode = Player.REPEAT_MODE_ONE
holder.vidPlayer.player = player
player.prepare()
player.seekTo(100)
// player.play()
holder.vidPlayer.setTag(mpTag, player)
holder.vidPlayer.setTag(manuelPlayTag, false)
holder.vidPlayer.setTag(manuelPauseTag, false)

player.addListener(object : Player.Listener { // player listener

    override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
        if (playWhenReady && playbackState == Player.STATE_READY) {
            Log.d(tagg, "state: plays")
            holder.vidPlayer.hideController()
        } else if (playWhenReady) {
            // might be idle (plays after prepare()),
            // buffering (plays when data available)
            // or ended (plays when seek away from end)
        } else {
            Log.d(tagg, "state: pause")
            holder.vidPlayer.showController()
        }
    }
})

how I prevent the play when app goes to background?

2 Answers

When your app goes to the background the active Fragment/Activity's Lifecycle method onPause (and onStop) is called. In the onPause method you can cycle through your bound ViewHolders and stop the video player(s).

You can simply stop the ExoPlayer when the app goes to the background.

override fun onStop() {
    super.onStop()
    simpleExoPlayer.stop()
}

And in onStart just prepare() the ExoPlayer again:

override fun onStart() {
    super.onStart()
    simpleExoPlayer.prepare()
}

In order to automatically play the media, you need to set playWhenReady = true.

simpleExoPlayer.playWhenReady = true

By setting playWhenReady = true it will automcatically play the content and we don't need to explicitly call simpleExoPlayer.play().

Related