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?
Your service should look like this