Android蓝牙开发权限报错:需显式检查权限或处理SecurityException
解决Android蓝牙权限报错:Call requires permission which may be rejected by user
问题原因
你遇到的报错根源是Android 12(API 31)及以上版本中,BLUETOOTH_CONNECT属于危险权限,仅在Manifest文件中声明权限无法满足系统要求,必须在代码中动态申请并确认用户授权后,才能调用isDiscovering()、disable()这类需要权限的蓝牙API。
解决方案
1. 添加权限检查与申请逻辑
在你的Activity中新增以下方法,用于检查和申请蓝牙权限:
// 检查蓝牙权限是否已授权 private boolean hasBluetoothPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { return ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED; } // 适配API31以下版本,使用旧权限规则 return ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) == PackageManager.PERMISSION_GRANTED; } // 动态申请蓝牙权限 private void requestBluetoothPermission() { String permission = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ? Manifest.permission.BLUETOOTH_CONNECT : Manifest.permission.BLUETOOTH_ADMIN; registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> { if (isGranted) { showToast("蓝牙权限已授权"); } else { showToast("需要蓝牙权限才能执行此操作"); } }).launch(permission); }
2. 修改点击事件代码
在调用蓝牙API前先检查权限,未授权则触发申请:
mDiscoverBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (hasBluetoothPermission()) { if(!mBlueAdapter.isDiscovering()){ showToast("Making your device Discoverable"); Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); mDiscoverBtLauncher.launch(intent); } } else { requestBluetoothPermission(); } } }); mOffBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (hasBluetoothPermission()) { if(mBlueAdapter.isEnabled()){ mBlueAdapter.disable(); showToast("Turning Bluetooth off"); mBlueTv.setImageResource(R.drawable.ic_action_off); } else { showToast("Bluetooth is already off"); } } else { requestBluetoothPermission(); } } });
3. 备选方案(不推荐)
如果不想处理动态申请逻辑,也可以用try-catch包裹蓝牙API调用,捕获SecurityException:
try { if(!mBlueAdapter.isDiscovering()){ // 原有业务逻辑 } } catch (SecurityException e) { showToast("缺少蓝牙权限,请授权"); requestBluetoothPermission(); }
内容的提问来源于stack exchange,提问作者Lee dong uk
相关产品推荐
相关产品推荐

