motoku
motoku

Reputation: 1581

Turn bluetooth on and wait for intent?

I have an Android App that requires some Bluetooth settings; see below:

if (!Constants.mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
while (!Constants.mBluetoothAdapter.isEnabled()) {
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        System.exit(1);
    }
}
if (Constants.mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
    Intent discoverableIntent = new
        Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
        startActivity(discoverableIntent);
}
while (Constants.mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        System.exit(1);
    }
} // do some stuff with bluetooth

This seems like a hack to me, and it only works if the user selects "yes". I'm pretty sure I need to be waiting on a result from these intents. How is that done?

Upvotes: 2

Views: 2835

Answers (1)

Tautvydas
Tautvydas

Reputation: 2067

You can call startActivityForResult() and implement onActivityResult() method which will be called when user returns from the called activity.

For the check whether Bluetooth is enabled change code to:

if (!Constants.mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
    progressToNextCheck();
}

Then in the progressNextCheck() implement your check for the Bluetooth discoverability in a similar manner.

private void progressToNextCheck(){
    if (Constants.mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
        Intent discoverableIntent = new        Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
        startActivityForResult(discoverableIntent, REQUEST_DISCOVERABLE_BT);
    } else {
        goToTheTask();
    }
}

And your onActivityResult() method:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (requestCode == REQUEST_ENABLE_BT) {
         if (resultCode == RESULT_OK) {
             progressToNextCheck();
         }
     } else if (requestCode == REQUEST_DISCOVERABLE_BT) {
         if (resultCode == RESULT_OK) {
             goToTheTask();
         }
     }
 }

Upvotes: 5

Related Questions