Search code examples
androidkotlinexoplayerexoplayer2.x

For how long will Exoplayer play in the background?


I have used Exoplayer to play an audio stream. You can see the code below. I am not a professional Android dev, but I know that on android if you want something to run in the background you have to use services. I did not expect this player to play in the background, but it does. My question is. Is this enough will the player work fine in the background, does exoplayer handle bacground mode by default, or will the player be shut down after a while. So is it still necessary to make a service that runs in the background?

private fun setUpPlayer(){
            val renderersFactory = DefaultRenderersFactory(this)
            val trackSelector = DefaultTrackSelector()
            exoPlayer = ExoPlayerFactory.newSimpleInstance(this, renderersFactory, trackSelector)
            val userAgent = Util.getUserAgent(this, "FOOBAR")
            val mediaSource = ExtractorMediaSource(Uri.parse(radioLink), DefaultDataSourceFactory(this, userAgent), DefaultExtractorsFactory(), null, null)
            exoPlayer.prepare(mediaSource)
            exoPlayer.playWhenReady = true
        }

Solution

  • You will need a service to run exoplayer, i have had experience with this when i was trying out exoplayer. First of all android will destroy your activity along with the instance of your exoplayer.

    On back press or in background the app will still be able to play but eventually after couple of minutes it will stop as android tries to free resources.

    It is actually very good to do things via service so you can do much without doing heavy task on your activity main thread.

    You just need a foreground service which also requires a notification with a specific channel, you can also make the notification of media style so you can control your playback through notification or even when the screen is locked.

    this tutorial explains how to work with service

    Why you need service (Quote from this article)?

    You should only use a foreground service when your app needs to perform a task that is noticeable by the user even when they're not directly interacting with the app.

    As per one of your comments it seem that while development the exoplayer is luckily alive but i would say once you deploy your app to different devices you may want to rethink on the approach of using activity or service for exoplayer.