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

迁移至Android 12 Target SDK32后,读取bluetooth_name在Pixel设备崩溃求助

问题原因

从Android 12(Target SDK 32)开始,系统限制第三方应用读取Settings.Secure.BLUETOOTH_NAME设置项,仅允许Target SDK版本≤31的应用访问该字段,这就是触发SecurityException的直接原因。

解决方案

改用蓝牙框架提供的合法API获取设备蓝牙名称,步骤如下:

  • 声明权限:在AndroidManifest.xml中添加蓝牙连接权限:
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    
  • 动态申请权限:BLUETOOTH_CONNECT在Android 12及以上属于危险权限,需在代码中动态向用户申请,示例代码:
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            ActivityResultLauncher<String[]> requestBluetoothPermission = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), result -> {
                Boolean connectGranted = result.getOrDefault(Manifest.permission.BLUETOOTH_CONNECT, false);
                if (connectGranted) {
                    // 权限获取成功,执行蓝牙名称读取逻辑
                    getBluetoothName();
                }
            });
            requestBluetoothPermission.launch(new String[]{Manifest.permission.BLUETOOTH_CONNECT});
        } else {
            getBluetoothName();
        }
    }
    
  • 读取蓝牙名称:权限通过后,调用蓝牙适配器API获取名称:
    private void getBluetoothName() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter != null) {
            String bluetoothName = bluetoothAdapter.getName();
            // 处理获取到的蓝牙名称
        }
    }
    
额外注意事项
  • 若设备未开启蓝牙,getName()可能返回null,建议先检查蓝牙状态,必要时引导用户开启蓝牙。
  • 该方案兼容Android 12及以上版本,同时适配低版本系统,无需区分Target SDK版本做分支处理。

内容的提问来源于stack exchange,提问作者Mahmoud Omara

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 07:06:21