2
votes

I want to play sound in an app only if it is NOT played through the phone's built in speaker. To do this, I assume I need to find out if there is an external speaker connected (wired speaker, bluetooth headset, wired headset, etc).

I see that AudioManager.isWiredHeadsetOn() is deprecated but still works, however this only shows that a wired headset is plugged in. Is there a similar option for bluetooth? Will that cover all the possible audio options?

Conversely, if there is a way to tell that sound WILL be routed through the built in speaker, that would probably work just as well.

2

2 Answers

0
votes
public static boolean isWiredHeadsetConnected() {    
        AudioManager mAudioMgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        if(mAudioMgr.isWiredHeadsetOn()){

                 mAudioMgr.setWiredHeadsetOn(false);
                 mAudioMgr.setSpeakerphoneOn(true);
                 mAudioMgr.setMode(AudioManager.MODE_IN_COMMUNICATION);

                 Toast.makeText(getApplicationContext(), "SpeakerPhone On", Toast.LENGTH_LONG).show();
          }
}

There's an intent to detect whether or not one is being plugged or unplugged: ACTION_HEADSET_PLUG. So, you must add it.

public static boolean isBluetoothHeadsetConnected() {
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()
            && mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED;
} 

Bluetooth permission:

<uses-permission android:name="android.permission.BLUETOOTH" />
0
votes

You must extend the OnAudioFocusChangeListenerclass. In it's onAudioFocusChange function, you will be notified of each and every event related to audio.

Changes in the state of an external speaker are monitored with the AudioManager.ACTION_HEADSET_PLUGconstant (it is provided to you as an onAudioFocusChange parameter ).