'How to enable/disable bluetooth in android java?

I tried various things other than this code, but it didn't work properly.

    private static final int REQUEST_ENABLE_BT = 1;
       
    BluetoothAdapter bluetoothAdapter= BluetoothAdapter.getDefaultAdapter();

    private static final int REQUEST_ENABLE_BT = 1;

    try {
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }catch(SecurityException d){
        d.printStackTrace();
    }


Solution 1:[1]

According to https://developer.android.com/training/basics/intents/result the using startActivityForResult method is no longer recommended. But if you do use it, you will need to use an onActivityResult to wait for the action to complete.

Your current code is not waiting ... so if you immediately try to use Bluetooth you are liable to find that it is still disabled.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stephen C