Bluetooth not disable programmatically in android API 31 or higher version

3.6k Views Asked by At

I'm trying to disable Bluetooth on the button click but it not work

hear, What I Do

if (SDK_INT >= Build.VERSION_CODES.S) {
    if (checkPermission(Manifest.permission.BLUETOOTH_CONNECT) && checkPermission(Manifest.permission.BLUETOOTH_SCAN)) {
        BluetoothAdapter adapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
        if (adapter != null) {
            if (adapter.getState() == BluetoothAdapter.STATE_ON) {
                Log.e("BT", "disable");
                adapter.disable();
            } else if (adapter.getState() == BluetoothAdapter.STATE_OFF) {
                if (!adapter.isEnabled()) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                }
                Log.e("BT", "enable");
            } else {
                Log.e("BT", "Else");
            }
        } else {
            Toast.makeText(UltimateHomeLauncherActivity.this, "Bluetooth is not supported on your hardware", Toast.LENGTH_SHORT).show();
        }
    } else {
        List<String> deniedPermissions = new ArrayList<>();
        deniedPermissions.add(Manifest.permission.BLUETOOTH_CONNECT);
        deniedPermissions.add(Manifest.permission.BLUETOOTH_SCAN);
        requestRuntimePermissions(1011, deniedPermissions.toArray(new String[0]));
    }
}

I'm add Bluetooth permission in Manifest also.

<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
2

There are 2 best solutions below

1
Risto On

android.permission.BLUETOOTH_CONNECT is a runtime permission and requires the consent of the user.

However, with next API level 33 enable()/disable() of the BluetoothAdapter will be deprecated and are not longer allowed. Therefore, it is probably best for such a function to navigate the user to the Bluetooth system dialog and ask him to turn the function on or off there.

1
Vishnu S Dharan On

There are two ways to turn on/off Bluetooth in Android

  1. BluetoothAdapter.enable() to turn on Bluetooth

    BluetoothAdapter.disable() to turn off Bluetooth

    These methods are asynchronous and will only work below API level 33

  2. Or use

{ Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, REQUEST_ENABLE_BT); }

to turn on Bluetooth

{ Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISABLE); startActivityForResult(intent, REQUEST_DISABLE_BT); }

to turn off Bluetooth

Upon execution, a system dialog will prompt the user to turn on/off Bluetooth.

Once turned on/off onActivityResult() override method will be triggered.

In your case, you are using BluetoothAdapter.disable() try using the other method.