I'm having trouble getting the external media buttons to work in my app while the activity is not visible.
The media buttons work correctly while the activity is visible. I can play and pause the player without any issues by pressing the media buttons (while the activity is visible).
As soon as I minimize the activity (by pressing the Home button), the app stops responding to the media buttons.
I know this question has been asked a couple of times but it seems that I'm missing something that the other questions don't cover.
Here's a minimal reproducible example: https://github.com/HectorRicardo/android-media-buttons-not-working-mre/commit/a4ea01bf29ba7289e055767c5c935e35b7fbbcff
(the left side of the diff is basically a blank project from scratch created in Android Studio, while the right contains the minimal reproducible example)
What I have done so far:
- I've made sure that the
PlaybackState
always contains theACTION_PLAY
,ACTION_PAUSE
, andACTION_PLAY_PAUSE
actions, for example:
mediaSession.setPlaybackState(playbackStateBuilder
.setState(PlaybackStateCompat.STATE_PLAYING, 0, 1)
.setActions(PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE)
.build())
- I've added a
MediaButtonReceiver
to my manifest:
<receiver android:name="androidx.media.session.MediaButtonReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
- I've updated the
onStartCommand
of myMediaBrowserService
:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
MediaButtonReceiver.handleIntent(mediaSession, intent);
return super.onStartCommand(intent, flags, startId);
}
I've made sure that the media session is active. Inside the
onPlay
method of theMediaSessionCompat.Callback
, I do:mediaSession.setActive()
.The
FLAG_HANDLES_MEDIA_BUTTONS
flag seems to be deprecated according to the reference docs. I tried adding it anyways, but it didn't help.
Not sure what else to check for. What am I missing?