media: Killing the app while audio is playing results in "The controller is not connected" and not being able to play again

Version

Media3 1.2.0

More version details

No response

Devices that reproduce the issue

  • OnePlus 7T Pro - Android 11
  • Pixel 4 Emulator - Api 33

Devices that do not reproduce the issue

No response

Reproducible in the demo app?

Not tested

Reproduction steps

  1. Open app and play audio
  2. Kill the app (swipe from recents)
  3. Reopen the app and try to play audio again

Expected result

The audio should play normmally

Actual result

Audio doesn’t play. Logs:

MediaController      The controller is not connected. Ignoring setMediaItem().
MediaController      The controller is not connected. Ignoring prepare().

If the app is killed a second time, then the audio will play normally. However the issue can be reproduced again.

Media

Not applicable

Bug Report

  • You will email the zip file produced by adb bugreport to android-media-github@google.com after filing this issue.

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 2
  • Comments: 23 (8 by maintainers)

Most upvoted comments

I’ve recently stumbled across the same problem. As described by @kelmer44 , this is reproducible when the instance is a singleton, but that does not mean it is a problem with the DI framework (FYI I was using Koin). The problem likely occurs due to a resource not being properly released in this specific scenario. Let me elaborate:

I need a single instance of the audio player in the app, so that audio playback can continue uninterrupted when switching between screens, but also allowing the user to interact with the audio player from different locations in the app. So, I opted in for using a singleton instance of the player. This instance is being released when the PlaybackService is destroyed, as described in the official documentation, or when the MainViewModel is destroyed (at this point I want to stop the playback). This works fine in most cases, except for the one described in this issue. Namely, when the audio player is playing and the app is force closed, then this problem can be reproduced. After some debugging, this are my findings:

  1. When the application is force closed, the player is released, the service is destroyed, yet the process remains alive;
  2. The next time the user opens the app, they are in the same process, hence using the instance of the audio player that has been already released;
  3. Trying to perform actions on the player that has already been released results in The controller is not connected. Ignoring *
  4. When the user closes the app, now the process ends as well;
  5. When the user opens the app again, everything is back to normal, as a new instance of the player has been created.

We do not see this problem when not using the singleton pattern, as you’d get a new instance of the player in step 2, rather than the one that has already been released. From this, we can conclude that this is not a problem with the DI.

Furthermore, I tried to see what happens if the process ends together with the service by killing the process manually when the onDestroy method of the service is called. In this case, everything works as expected as the next time the user opens the app, they are in a new process with a new instance of the player. But, of course, this is not a solution to the problem, just a way to prove the theory.

So, the question is: why does the OS keep the process alive when force closing the app while audio is playing, but kills the process when audio is not playing? 🤔 Possibly some unreleased resources?

Here’s a simplified summary of the problem I faced and how I worked around this issue in my case:

class AudioPlayer(
    private val context: Context,
) {
    private val sessionToken =
        SessionToken(context, ComponentName(context, PlaybackService::class.java))
    private val factory = MediaController.Builder(context, sessionToken).buildAsync()
    
    private var player: Player? = null

    init {
        factory.addListener({
            player = factory?.get()
    })

    fun release() {
        MediaController.releaseFuture(factory)
        player?.release()
    }
}
class MainViewModel(
    private val audioPlayer: AudioPlayer, //this is injected as singleton instance
) : ViewModel() {
     
    override onCleared() {
        super.onCleared()
        audioPlayer.release()
    }
}
class PlaybackService : MediaSessionService() {
    private var mediaSession: MediaSession? = null

     override fun onCreate() {
        super.onCreate()
        val player = ExoPlayer.Builder(this).setPauseAtEndOfMediaItems(true).build()
        mediaSession = MediaSession.Builder(this, player)
            .setCallback(CustomMediaSessionCallback())
            .build()
    }

    override fun onTaskRemoved(rootIntent: Intent?) {
        val player = mediaSession?.player!!
        if (player.playWhenReady) {
            player.stop()
        }
        stopSelf()
    }

    override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? =
        mediaSession


    override fun onDestroy() {
        Log.i("PlaybackService", "onDestroy")
        mediaSession?.run {
            player.release()
            release()
            mediaSession = null
        }
        super.onDestroy()
    }
}

And here’s the result with this setup: MediaController

In order to work around the issue, I made a couple of changes:

  1. Instead of making the connection with the service once, in the init block of the singleton AudioPlayer, I’ve moved this logic to an init method
class AudioPlayer(
    private val context: Context,
) : AudioPlayer {
    private var factory: ListenableFuture<MediaController>? = null
    private var player: Player? = null

    fun init() {
        val sessionToken =
            SessionToken(context, ComponentName(context, PlaybackService::class.java))
        factory = MediaController.Builder(context, sessionToken).buildAsync()
        factory?.addListener( { 
            player = factory?.get()
        })
    }

   fun release() {
        factory?.let { MediaController.releaseFuture(it) }
        player?.release()
    }
}
  1. In the MainViewModel, I call the init method in the init block of the view model.
class MainViewModel(
    private val audioPlayer: AudioPlayer, //this is injected as singleton instance
) : ViewModel() {
     
    init { audioPlayer.init() }

    override onCleared() {
        super.onCleared()
        audioPlayer.release()
    }
}

With these changes, I have a singleton instance of my own AudioPlayer implementation, while the actual media3 player used for the reproduction is created for every session, rather than every process. This is how the changes affect the app behavior:

MediaController (1)

With this setup I was able to keep the desired effects of a single audio player in the application. I hope it helps some of you that are facing the same issue 🙂

The last two suggestions would theoretically work but it’s not easy to implement on larger projects where these components are all over the place with lots of legacy code.

As the issue is still open and can be reproducible, I wonder if there are any investigation/work related to this issue.

I don’t have plans to investigate the Dagger implementation I’m afraid. The reason is simply that I don’t have dagger experience.

Yes I fully understand that, I was posting a follow-up for awareness of everyone involved 😃 However I do believe Dagger is a de-facto DI standard and universally used in Android so this issue is probably going to impact more implementors IMO.

Are you seeing the same problem with UAMP without Dagger?

Nope.

I’m experiencing this very issue with some of my components being declared as @Singleton using Dagger. Looks like this somehow prevents the MediaLibraryService from being garbage collected thus leaking it.

Installing LeakCanary on @k-arabadzhiev’s UAMP dagger branch, MusicService is reportedly being leaked:

Screenshot_20240313_155323

Somehow this seems easier to repro on Samsung devices in my experience.

A bit more context.

Our app has been migrating to media3 for some time now and we are facing a weird issue with MusicServiceConnection when using dagger2 singleton injection. I’m not absolutely certain that the issue is in media3, but it wasn’t happening with androidx.media that we had previously. Also I was able to reproduce the issue (to some degree) using UAMP and I’ll explain the differences with our app as in depth as I can.

The issue

Killing the app (swipe from recents) while audio is playing, reopening and trying to play again will result in audio not being able to start.

Here is what I found in the logs on the second app launch:

MediaController      The controller is not connected. Ignoring setMediaItem().
MediaController      The controller is not connected. Ignoring prepare().

Killing the app a second time, reopening and trying to play will work.

Pausing the app manually (from the app itself or notification player) before killing it will not cause the issue. However, pausing the player in code (in onTaskRemoved for example) will not solve the issue.

The workaround that we’re currently using is to not use dagger’s singleton scope, but instead instantiate the MusicServiceConnection using companion object like it’s done in UAMP

Here is my fork of UAMP where I’ve reproduced the issue. In this branch a lot of libraries are updated, including media3 and dagger2 dependency injection is implemented as well.

UAMP is architecturally very different from our app, because the whole UI depends on the root media item. So after killing the app while the audio is playing the result will be that the UI is not even rendering. I think that’s the reason I can’t see in the logs The controller is not connected - because I can’t even get to play anything, but the root cause of the issue should be the same.

Any idea why is this happening? Why singleton injection doesn’t work, but the companion object snippet that looks like a hack is working?