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

Android 12中Bluetooth ACL_CONNECTED/AC_DISCONNECTED广播接收器失效问题

Android 12 中蓝牙ACL连接状态广播接收器不触发的解决方案

在Android 12(API 31)及更高版本中,系统对蓝牙相关权限做了严格限制,你的代码无法触发广播接收器的核心原因是缺少必要的运行时权限。以下是具体的修复步骤:

1. 在Manifest中声明权限

首先需要在AndroidManifest.xml里添加蓝牙相关权限:

<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-feature android:name="android.hardware.bluetooth" android:required="false" />

2. 动态申请BLUETOOTH_CONNECT权限

由于BLUETOOTH_CONNECT属于危险权限,必须在运行时向用户申请:

private const val REQUEST_BLUETOOTH_PERMISSION = 1001

// 在合适的时机(如Activity onCreate)检查并申请权限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.BLUETOOTH_CONNECT),
            REQUEST_BLUETOOTH_PERMISSION
        )
    } else {
        registerBluetoothReceiver()
    }
} else {
    // Android 12以下版本直接注册接收器
    registerBluetoothReceiver()
}

3. 处理权限申请结果

在Activity中重写权限回调方法,确保权限通过后再注册接收器:

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if (requestCode == REQUEST_BLUETOOTH_PERMISSION) {
        if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            registerBluetoothReceiver()
        } else {
            Toast.makeText(this, "需要蓝牙权限才能检测设备连接状态", Toast.LENGTH_SHORT).show()
        }
    }
}

4. 调整广播接收器注册逻辑

把注册逻辑封装到单独方法中,确保只有权限通过时才执行:

private fun registerBluetoothReceiver() {
    val filter = IntentFilter().apply {
        addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
        addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
    }
    registerReceiver(broadCastReceiver, filter)
}

private val broadCastReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        val action = intent?.action
        when (action) {
            BluetoothDevice.ACTION_ACL_CONNECTED -> {
                coroutineScope.launch {
                    delay(6000)
                    deviceHelper.configAudioManager(true, true)
                }
            }
            BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
                deviceHelper.configAudioManager(false, true)
            }
        }
    }
}

额外注意事项

  • 若在后台Service中注册广播,需确保Service符合Android 12的后台运行限制,避免被系统回收。
  • 测试时必须使用Android 12及以上设备,验证权限申请流程与广播触发逻辑是否正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:15:07