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?
Bluetooth device volume can be changed from either a connected phone or a Bluetooth device by pressing the volume control button.
Absolute volume control In Android 6.0 and later, the Android Bluetooth stack lets a source set an absolute volume, giving users accurate control over audio volume. The source device sends un-attenuated audio and volume information to the sink.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With