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
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:
This ensures that changes in the bound clients do not cause the Service to be destroyed mid-playback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With