Skip to content

Instantly share code, notes, and snippets.

@kwong93
Last active June 24, 2020 10:48
Show Gist options
  • Save kwong93/642bb05ead3f33725f1fb57ef54d98b0 to your computer and use it in GitHub Desktop.
Save kwong93/642bb05ead3f33725f1fb57ef54d98b0 to your computer and use it in GitHub Desktop.
How to handle button clicks on notification for playing media in service using media session
// Took forever because of crappy tutorials, for example https://developer.android.com/guide/topics/media-apps/audio-app/building-a-mediabrowserservice.html
// Key information was in COMMENTS in MediaButtonReceiver.java
// The key is to have a receiver with filter android.intent.action.MEDIA_BUTTON AND in the service
// register pending intent to the button in notification
builder.addAction(new NotificationCompat.Action(
R.drawable.ic_skip_next_black_24dp, getString(R.string.skip_next),
MediaButtonReceiver.buildMediaButtonPendingIntent(this, PlaybackStateCompat.ACTION_SKIP_TO_NEXT)));
// manifest changes
<service
android:name=".PlayerService">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
<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>
// in onStartCommand of the service
MediaButtonReceiver.handleIntent(mediaSessionCompat, intent);
// THEN you will be able to listen for events from setCallback when media session was created
mediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
playbackStateBuilder = new PlaybackStateCompat.Builder();
playbackStateBuilder.setActions(PlaybackStateCompat.ACTION_PLAY); // add more actions here, like skip next, previous, etc
mediaSessionCompat.setPlaybackState(playbackStateBuilder.build());
mediaSessionCompat.setCallback(mediaSessionCallback); // this won't listen without the manifest additions
mediaSessionCompat.setActive(true);
@remcoder
Copy link

remcoder commented Jul 4, 2018

Thanks a lot! I was banging my head against the wall b/c I didn't know what I missed. But thanks to this snippet I got it working now :D

@muiz6
Copy link

muiz6 commented Jun 24, 2020

Thanks worked when I followed this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment