0

I cannot figure out how to wait for the user the to choose whether or not to enable bluetooth. If the app starts without bluetooth enabled it crashes because I am not waiting for the result from this line:

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

How can I wait until the user selects yes or no to enabling Bluetooth? -Thanks

user3831011
  • 309
  • 1
  • 10
  • You don't do anything in your app until `onActivityResult()` is called. You may need to set a flag in your Activity that you are waiting for the user, so that you don't do anything with Bluetooth until the user responds. – David Wasser Apr 17 '15 at 18:06
  • Are you overriding `onActivityResult()`? – codeMagic Apr 17 '15 at 18:06
  • relevant http://stackoverflow.com/questions/20558689/back-to-previous-activity-with-intent/20558774#20558774 – codeMagic Apr 17 '15 at 18:39

1 Answers1

3

You have to override onActivityResult as described in this article.

http://developer.android.com/training/basics/intents/result.html

This is the general flow:

  1. You start another activity for result in the fashion you posted
  2. Once the called activity finishes it should return the result to the calling activity via onActivityResult method.

You should check the result or check if bluetooth is turned on after that method is called for ex. and continue your execution based on the information you now have.

Code snippets from the article:

static final int PICK_CONTACT_REQUEST = 1;  // The request code

private void pickContact() {
   Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
   pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
   startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
 if (requestCode == PICK_CONTACT_REQUEST) {
    // Make sure the request was successful
    if (resultCode == RESULT_OK) {
        // The user picked a contact.
        // The Intent's data Uri identifies which contact was selected.

        // Do something with the contact here (bigger example below)
    }
 }
}
JanBo
  • 2,925
  • 3
  • 23
  • 32