安卓 : Deny button pressed on Bluetooth enabling dialog box

标签 android bluetooth

如何处理蓝牙启用对话框中的“拒绝”按钮?我尝试使用 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);
        }
    }

此代码会提示用户对话框,直到他按下“允许”或“确定”按钮,但一旦他按下“< strong>拒绝”或“取消”按钮。我该怎么做呢?当我按下“拒绝”按钮时,是否会调用任何函数?

最佳答案

您需要重写 onActivityResult 方法。

您正在使用常量 REQUEST_ENABLE_BT 传递 requestCode

因此,当用户在该 onActivityResult 方法之后按下允许或拒绝按钮时,将从您的 Activity 中调用。

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

关于安卓 : Deny button pressed on Bluetooth enabling dialog box,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20652211/

相关文章:

android 文本文件导入 我在哪里保存文本文件什么文件夹?

ios - 仅广告数据与连接 BLE 设备的优势

java - 不幸的是,该应用程序在 Android 中已停止工作错误

java - 无法解析符号 'ActivityCompat' 和 'content'

android - 我们如何创建动态 TextView ?

ios - 通过串行端口配置文件 (SPP) 与 iOS 设备通信是否需要 MFi 芯片

java - 如何检测蓝牙设备是否超出范围,或者我们丢失了它?

ios - 当应用程序在后台时与 iOS 中的蓝牙经典设备通信?

java - 如何仅使用公共(public)函数和成员生成可分发的库 jar?

java - 在android中将字符串数组的ArrayList从一个 Activity 传递到另一个 Activity