Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MediaBrowserServiceCompat instance is recreated every runtime changes

I have a Service using the new MediaBrowserServiceCompat to interact with my Player implementation.

Here's my service's onCreate()

@Override
public void onCreate() {
    super.onCreate();

    audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    initMediaSession();
    initMediaPlayer();

}

and my initMediaSession()

private void initMediaSession() {
    Log.d(TAG, "initMediaSession: ");
    mediaSessionCompat = new MediaSessionCompat(getApplicationContext(), TAG);
    mediaSessionCompat.setCallback(new MediaSessionCompat.Callback() {
        // I override the methods here
    });
    mediaSessionCompat.setActive(true);

    // Method from MediaBrowserServiceCompat
    setSessionToken(mediaSessionCompat.getSessionToken());
}

I then access my MediaBrowserCompat in my Activity:

@Override
public void onCreate() {
    mediaBrowser = new MediaBrowserCompat(this, new ComponentName(this, MediaPlaybackService.class), mediaBrowserConnectionCallback, null);
    mediaBrowser.connect();
}



// I do stuff here



@Override
protected void onDestroy() {
    super.onDestroy();
    if (mediaBrowser != null) {
        mediaBrowser.disconnect();
    }
}

Every time mediaBrowser.connect() is called my service is created and killed when mediaBrowser.disconnect() is called.

The problem is when the MediaSessionCompat is recreated I lose any metadata I created or playback state I might have saved.

Is it the way it is supposed to be or mm I doing it wrong ?

Also If it is supposed to be that way does it mean I have to save my metadata somewhere and recall MediaSessionCompat.setMetadata() every time I create a new MediaSessionCompat object? or is there a more efficient solution ?

Thank you

like image 694
Charles-Eugene Loubao Avatar asked Dec 13 '25 15:12

Charles-Eugene Loubao


1 Answers

As mentioned in the MediaBrowserService and the modern media playback app blog:

this wraps the API for bound services, which makes sense since we’re trying to connect to a Service.

The lifecycle of a bound service is tied directly to who binds to the service:

When the last client unbinds from the service, the system destroys the service (unless the service was also started by startService()).

In your case, the service will no longer have anyone bound to it between onDestroy() and onCreate().

The example of Universal Android Music Player's MusicService is to:

  • Call startService(new Intent(this, MediaPlaybackService.class) when playback begins
  • Call stopSelf() when playback is stopped

This ensures that changes in the bound clients do not cause the Service to be destroyed mid-playback.

like image 138
ianhanniballake Avatar answered Dec 16 '25 04:12

ianhanniballake