Pre API 21 I was using a call like audioManager.registerMediaButtonEventReceiver(receiver);
to handle media button events when a user pressed a button on his headset. As of API 21, it seems that MediaSession
should be used. However, I'm not getting any response whatsoever.
final MediaSession session = new MediaSession(context, "TAG");
session.setCallback(new Callback() {
@Override
public boolean onMediaButtonEvent(final Intent mediaButtonIntent) {
Log.i("TAG", "GOT EVENT");
return super.onMediaButtonEvent(mediaButtonIntent);
}
});
session.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
session.setActive(true);
Above is what I think should work but doesn't. Does anyone know why this isn't working or how I should register?
To receive media button events, you need to:
set a MediaSession.Callback and handle the proper events (*)
set MediaSession.FLAG_HANDLES_MEDIA_BUTTONS
and MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS
flags
set the mediaSession to active
set a playbackstate properly, in special the actions (playback events) that your session handles. For example:
PlaybackState state = new PlaybackState.Builder()
.setActions(
PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PLAY_PAUSE |
PlaybackState.ACTION_PLAY_FROM_MEDIA_ID | PlaybackState.ACTION_PAUSE |
PlaybackState.ACTION_SKIP_TO_NEXT | PlaybackState.ACTION_SKIP_TO_PREVIOUS)
.setState(PlaybackState.STATE_PLAYING, position, speed, SystemClock.elapsedRealtime())
.build();
mSession.setPlaybackState(state);
My guess is that you are missing #4, because you are doing everything else correctly.
(*) the default implementation of Callback.onMediaButtonEvent handles all common media buttons and calls the proper onXXXX() methods (onPlay, onPause, onSkipToNext, etc). Unless you need to handle uncommon media buttons - or for debugging purposes -, you don't need to override onMediaButtonEvent.
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