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
Have you registered a BroadcastReceiver
in your app to listen to MEDIA_BUTTON
events using 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:
@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.
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).
Please note that this API has changed since the accepted answer was written. Please refer to the MediaSession callbacks documentation.