Previously, we introduced How to add audio device action sheet to your iOS app, I believe there is the same need for android app. So here we go again.
Similar to iOS devices, there are 3 typical audio routes: DEFAULT, SPEAKER, BLUETOOTH.
The DEFAULT route is the handset and will become wired headset if there is a plugged one.
Let’s see how to configure out the current route on the android device.
DEFAULT wired headset
We will need to listen to the broadcast intent: ACTION_HEADSET_PLUG.
SPEAKER
We can directly get from AudioManager:
AudioManager.isSpeakerphoneOn()
BLUETOOTH
We can also directly get from AudioManager:
AudioManager.isBluetoothScoOn()
But usually, you will want to know if there is any bluetooth devices connected, then determine your UI to show this audio option or not. We can register listener to the Bluetooth Adapter.
We can also listen to the broadcast : ACTION_SCO_AUDIO_STATE_UPDATED
With the above listeners, you can update your audio device menu whenever there is a bluetooth headset plugged in, and can fallback the audio route when the current bluetooth has plugged out.
So we know how to collect the available audio devices, now let’s see how to bring up the action sheet menu using BottomSheetDialog.
How to change audio route
So how to change the audio route whenever the user clicks on the desired route? It’s quite simple.
Bluetooth
AudioManager.startBluetoothSco();
AudioManager.setBluetoothScoOn(true);
Speaker
AudioManager.setSpeakerphoneOn(true);
Default
This is an interesting one. Because there is no ‘setDefaultOn’, but we can achieve by turning off other routes.
AudioManager.setSpeakerphoneOn(false);AudioManager.stopBluetoothSco();
AudioManager.setBluetoothScoOn(false);
That’s it! Feel free to share your thoughts or feedback.