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?
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With