Android : Deny button pressed on Bluetooth enabling dialog box

Viewed 2580

How do i handle the "Deny" button press on Bluetooth enabling Dialog box? I tried using OnDismissListener and OnCancelListener even tried onActivityResult but didn't work. The code is:

    private BluetoothAdapter mBluetoothAdapter;
    private static final int REQUEST_ENABLE_BT = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (isBleSupportedOnDevice()) {
            initializeBtComponent();

        } else {
            finish();
        }
    }

    private boolean isBleSupportedOnDevice() {
        if (!getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "BLE is not supported in this device.",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void initializeBtComponent() {
        final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }

This code prompts user with the dialog until he presses the "Allow" or "OK" button but i have to get back to previous activity once he presses "Deny" or "Cancel" button. How do i do this? is there any function that gets called when i press the "Deny" button?

2 Answers

To solve this, you simply check for RESULT_CANCELED in your onActivityResult() callback. Some thing like this:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==REQUEST_ENABLE_BT && resultCode==RESULT_CANCELED){
        ... Do your stuff...
    }
}
Related