Last active
June 24, 2020 10:48
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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