安卓:在蓝牙启用对话框中按下拒绝按钮

4

我该如何处理蓝牙启用对话框中的 "拒绝" 按钮按下事件?我尝试使用 OnDismissListenerOnCancelListener,甚至尝试了 onActivityResult,但并没有起作用。以下是代码:

    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);
        }
    }

这段代码会显示一个对话框,直到用户按下“允许”或“确定”按钮,但当他按下“拒绝”或“取消”按钮后,我想要回到之前的活动。我该怎么做?是否有任何函数在按下“拒绝”按钮时被调用?

我也遇到了同样的问题。你有得到任何答案吗? - sagar potdar
2个回答

1
你需要重写onActivityResult方法。
你正在使用常量REQUEST_ENABLE_BT传递requestCode。
因此,每当用户在按下允许或拒绝按钮后,将从您的活动调用onActivityResult方法。
@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  if(requestCode == REQUEST_ENABLE_BT){
   startBluetoothStuff();
  }

 }

在上述代码中,检查回调是否针对相同的请求代码。
因此,您的理想流程将类似于以下内容。
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);
   }
}

2
谢谢您的回复。我尝试了这种方法,问题是“onResume”方法每次在“onActivityResult”方法之前被调用。因此,用户会一遍又一遍地看到对话框。 - Rana Ranvijay Singh

0
为了解决这个问题,你只需要在你的 onActivityResult() 回调函数中检查 RESULT_CANCELED。像这样:

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...
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接