Reputation: 952
I want to use the media buttons to control a foreground app, but not for audio use. So the goal is to detect button clicks to do certain things in the app.
I can achieve that by using MediaSession
and the MediaButtonReceiver
. see here
The problem is that when the app is used, often users play music in the background, so the audio focus of the background app takes over the MediaSession and i cannot control my app anymore.
Is there a way to achieve that? Directly listening for button clicks with onKeyDown
does not seem to work.
Upvotes: 0
Views: 414
Reputation: 19243
sadly there is no way for two active MediaSession
s at the same time. if another app is playing music and run MediaSession
then yours doesn't have focus and isn't active... this is made for purpose - better UX - only one "player" app can play music (or video). if this wouldn't work like that and you could play music by few apps at once then how should work media button on e.g. headphones? pasuing/resuming all players? this is just not user-friendly, so Android team introduced MediaSession
pattern with option for calling "focus on me now" by any app, but then another app/MediaSession
pauses and doesn't get any inputs (this active session does)
if you need physical buttons presses then onKeyDown
should work (inside Activity
or eventually using AccessibilityService
, which would work "globally" in whole system). if you need some on-screen notification buttons presses then just make custom layout for your notification with as much buttons as you like, even styled as a player
note that in Android 11 active MediaSession
s notification is stickied to top of notification section when you drop down status bar. your custom notification will be somewhere below between all others (you can manipulate position a bit using priority param for notification/channel)
Upvotes: 1