Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling media buttons in Android 5.0 Lollipop

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?

like image 646
tvkanters Avatar asked Nov 18 '14 16:11

tvkanters


1 Answers

To receive media button events, you need to:

  1. set a MediaSession.Callback and handle the proper events (*)

  2. set MediaSession.FLAG_HANDLES_MEDIA_BUTTONS and MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS flags

  3. set the mediaSession to active

  4. 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.

like image 182
mangini Avatar answered Oct 04 '22 19:10

mangini