Reputation: 3956
I employed this guide to add MediaButtonReceiver
feature to my media player app.
It works well so far the app is in forebackground, but as soon as the app enters background it stops receiving media button actions.
Part of manifest
<service
android:name=".playback.PlayerService"
android:exported="true">
<intent-filter>
<action android:name="android.media.browse.MediaBrowserService"/>
</intent-filter>
</service>
<receiver android:name="android.support.v4.media.session.MediaButtonReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON"/>
</intent-filter>
</receiver>
Part of media player service
@Override
public void onCreate() {
Timber.d("onCreate: ");
super.onCreate();
startService(new Intent(getApplicationContext(), PlayerService.class));
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Timber.d("onStartCommand: ");
sessionCompat = new MediaSessionCompat(this, TAG);
setControllerCompat(new MediaControllerCompat(getApplicationContext(), sessionCompat));
sessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS |
MediaSessionCompat.FLAG_HANDLES_QUEUE_COMMANDS);
sessionCompat.setCallback(sessionCallback);
setSessionToken(sessionCompat.getSessionToken());
sessionCompat.setShuffleMode(playerHelper.getShuffleMode());
sessionCompat.setRepeatMode(playerHelper.getRepeatMode());
MediaButtonReceiver.handleIntent(sessionCompat, intent);
return START_NOT_STICKY;
}
Please what did I do wrong and how can I make the service receive button actions when the app is in foreground?
Upvotes: 3
Views: 6452
Reputation: 3956
I have discovered the problem. I made the very stupid mistake of not calling MediaSessionCompat#setActive(true) when the playback has started.
Upvotes: 2
Reputation: 192
Your service should look like this
<service android:name=".playback.PlayerService"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
<action android:name="android.media.browse.MediaBrowserService" />
</intent-filter>
</service>
Upvotes: 2