You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android 12(API 31)startActivityForResult与BLUETOOTH_CONNECT权限问题解决

解决Android 12+蓝牙启用时的SecurityException及startActivityForResult废弃问题

问题场景

升级至Android 12后,启用蓝牙功能时应用抛出SecurityException(提示需BLUETOOTH_CONNECT权限),同时原有startActivityForResult方法已被废弃,最终导致应用崩溃。

适配方案(Android 12+验证有效)

  1. 在AndroidManifest.xml中声明蓝牙权限
    添加必要的蓝牙权限,确保应用具备访问蓝牙功能的基础权限:

    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE"/>
    
  2. 运行时请求BLUETOOTH_CONNECT权限
    修改蓝牙启用方法bluetoothOn(),先检查权限状态,未授权则发起请求,再执行蓝牙启用逻辑:

    private void bluetoothOn() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) 
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, 
                new String[]{Manifest.permission.BLUETOOTH_CONNECT}, REQUEST_ENABLE_BT);
            return;
        }
    
        if (!mBTAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            bluetoothLauncher.launch(enableBtIntent);
        } else {
            Toast.makeText(getApplicationContext(),"Bluetooth is already on", Toast.LENGTH_SHORT).show();
        }
    }
    
  3. 处理权限请求结果
    重写onRequestPermissionsResult方法,根据用户权限授予结果执行对应逻辑:

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_ENABLE_BT) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                bluetoothOn();
            } else {
                Toast.makeText(this, "Permission denied to access Bluetooth", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
  4. 用ActivityResultLauncher替代startActivityForResult
    适配Android 12的API变更,使用ActivityResultLauncher替代已废弃的startActivityForResult,处理蓝牙启用的结果回调:

    ActivityResultLauncher<Intent> bluetoothLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK) {
                    mBluetoothStatus.setText("Enabled");
                } else {
                    mBluetoothStatus.setText("Disabled");
                }
            }
    );
    

内容的提问来源于stack exchange,提问作者Fischer Fritz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 16:15:27