Home:ALL Converter>How to check if Bluetooth headphones connected before asking permission

How to check if Bluetooth headphones connected before asking permission

Ask Time:2022-07-25T02:29:34         Author:Mike Keskinov

Json Formatter

It's now required to check BLUETOOTH_CONNECT permission in runtime when targeting Android 12 or higher (see here).

My app using Bluetooth only to connect to currently connected headphones (to redirect an audio to Bluetooth headphones during WebRTC conference call). So, I don't need to request the permission if a user do not use any Bluetooth headphones.

I know how to request permission, but the problem is that to check if the headphones connected, I first need to request the permission. But I don't want to request permission if no headphones connected.

As I understand, if I ask for permission as recommended, then all users would be asked to grand the permission even if they don't use Bluetooth headphones in my game. This is an unnecessary permission to ask a user and they won't thanks us for it.

But without checking for permission first, checking the status of headphones (connected or not) becomes impossible. How to resolve the catch 22?

This is my code to check if Bluetooth headphones connected:

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

enter image description here

Author:Mike Keskinov,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/73101011/how-to-check-if-bluetooth-headphones-connected-before-asking-permission
yy