Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to wait till bluetooth turn on in android

I need to turn on Bluetooth in an android device programmatically and wait till it on to proceed to next line of code.

My code is as below

if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                ctx.startActivity(enableBtIntent);
}

When doing like this, the code continue to execute from next line without waiting for bluetooth completely on. Is there any way to solve this? Can I add a look to check if bluetooth is on?

like image 370
Vineesh Avatar asked Nov 29 '22 23:11

Vineesh


2 Answers

You can register a BroadcastReceiver to listen for state changes on the BluetoothAdapter.

First create a BroadcastReceiver that will listen for state changes

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                                                BluetoothAdapter.ERROR);
            switch (bluetoothState) {
            case BluetoothAdapter.STATE_ON:
                //Bluethooth is on, now you can perform your tasks
                break;
            }
        }
    }
};

Then register the BroadcastReceiver with your Activity when it is created so that it can start receiving events.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Set a filter to only receive bluetooth state changed events.
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mReceiver, filter);
}

Remember to unregister the listener when the Activity is destroyed.

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(mReceiver);
}
like image 158
the-ginger-geek Avatar answered Dec 04 '22 14:12

the-ginger-geek


You can use startActivityForResult() and check for whether resultCode is RESULT_OK in onActivityResult() with bluetooth permission in your Manifest file like..

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableIntent, 0);
}

onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == RESULT_OK){
        // bluetooth enabled                      
    }else{
        // show error
    }       
}

ACTION_REQUEST_ENABLE

like image 32
Iamat8 Avatar answered Dec 04 '22 13:12

Iamat8