Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 714
Jason Robinson Avatar asked Nov 09 '11 22:11

Jason Robinson


People also ask

How do I control Bluetooth volume?

Bluetooth device volume can be changed from either a connected phone or a Bluetooth device by pressing the volume control button.

When using Bluetooth audio what controls the overall volume?

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.


1 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.

like image 163
Joe Avatar answered Sep 29 '22 11:09

Joe