Bluetooth audio controls in Android
Bluetooth audio controls in Android
My app streams music and I want to be able to pause/play/skip from any Bluetooth device that might support these buttons (car, headset, etc). When connected through a car's bluetooth the audio comes through automatically, but the control buttons do not affect my app's audio stream. It instead opens the default media player. How do I route these buttons to affect my app?
3 Answers
3
Have you registered a BroadcastReceiver
in your app to listen to MEDIA_BUTTON
events using AudioManager.registerMediaButtonEventReceiver()
?
BroadcastReceiver
MEDIA_BUTTON
AudioManager.registerMediaButtonEventReceiver()
After registering, the button events can be handled by processing the KeyEvent
object attached in the extras as EXTRA_KEY_EVENT
. For example:
KeyEvent
EXTRA_KEY_EVENT
@Override
public void onReceive(Context context, Intent intent) {
final KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event.getAction() != KeyEvent.ACTION_DOWN) return;
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_MEDIA_STOP:
// stop music
break;
case KeyEvent.KEYCODE_HEADSETHOOK:
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
// pause music
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
// next track
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
// previous track
break;
}
}
This Android Developer blog post also have some nice information on the subject.
I saw
MEDIA_BUTTON
events coming through the log, so this looks promising. I'll give it a go tomorrow.– Jason Robinson
Nov 10 '11 at 22:52
MEDIA_BUTTON
Further to the accepted answer, please be aware that one of the Keycodes has changed in Ice Cream Sandwich:
The keycode that gets passed for play/pause intent has changed in
ICS. See this
http://code.google.com/p/media-button-router/issues/detail?id=10#c5
The keycode that had been sent prior to ICS was
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE. Now there are two separate keycodes
for play and pause (126 and 127).
It's sending KEYCODE_MEDIA_PLAY (126) and KEYCODE_MEDIA_PAUSE (127).
https://code.google.com/p/android/issues/detail?id=23172
Please note that this API has changed since the accepted answer was written. Please refer to the MediaSession callbacks documentation.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Hi, Can you share example code for this same ?
– Hardik Joshi
May 9 '14 at 7:12