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

时间:2013-12-18 07:39:02

标签: android bluetooth

如何按蓝牙启用对话框按“拒绝”按钮。我厌倦了使用“ OnDismissListener ”和“ OnCancelListener ”,甚至试过“ 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);
            }
}

此代码会提示用户输入对话框,直到他按下“允许”或“确定”按钮,但是一旦按下“我必须返回上一个活动” 拒绝“或”取消“按钮。我该怎么做,当我按下“拒绝”按钮时,是否有任何功能被调用。

2 个答案:

答案 0 :(得分: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);
   }
}

答案 1 :(得分: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...
    }
}