Reputation: 6155
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?
Upvotes: 4
Views: 2793
Reputation: 179
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...
}
}
Upvotes: 0
Reputation: 6092
You need to override onActivityResult method.
You are passing requestCode using constant REQUEST_ENABLE_BT
So when ever user presses the Allow or Deny button after that onActivityResult method will get called from your activity.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
startBluetoothStuff();
}
}
In above code check whether callback is for same request code.
So your ideal flow will be like something this
boolean isBluetoothManagerEnabled()
{
// Some code
}
public void startBluetoothStuff()
{
if(isBluetoothManagerEnabled())
{
// Do whatever you want to do if BT is enabled.
}
else
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
Upvotes: 1