我编写了以下代码来实现绑定蓝牙设备并获取蓝牙设备绑定状态,但是我无法接收BroadcastReceiver消息,
Log.e("Bluetooth", "onReceive")
永远不会登录!
@SuppressLint("MissingPermission")
suspend fun Context.obtainBluetoothDeviceBondState(): Boolean {
return suspendCancellableCoroutine { continuation ->
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.e("Bluetooth", "onReceive")
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED == intent?.action) {
val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
val bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE)
if (macAddress == device?.address) {
when (bondState) {
BluetoothDevice.BOND_BONDED -> {
Log.e("Bluetooth", "bond bluetooth device success")
unregisterReceiver(this)
continuation.resume(true)
}
BluetoothDevice.BOND_NONE -> {
Log.e("Bluetooth", "bond bluetooth device failed")
unregisterReceiver(this)
continuation.resume(false)
}
}
}
}
}
}
continuation.invokeOnCancellation {
Log.e("Bluetooth", "unregisterReceiver")
unregisterReceiver(receiver)
}
Log.e("Bluetooth", "registerReceiver")
ContextCompat.registerReceiver(
this, receiver, IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED), ContextCompat.RECEIVER_NOT_EXPORTED
)
val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
if (!bluetoothManager.adapter.bondBluetoothDevice(macAddress)) {
continuation.resume(false)
}
}
}
@SuppressLint("MissingPermission")
fun BluetoothAdapter.bondBluetoothDevice(macAddress: String) = getRemoteDevice(macAddress).createBond()
kotlin版本是1.9.24,kotlin协程jvm版本和kotlin协程android版本只是1.6.4
我不知道为什么我没有收到BroadcastReceiver消息。有人有想法吗?
为了确保您的 BroadcastReceiver 可以接收系统事件,请使用 ContextCompat.RECEIVER_EXPORTED 标志而不是 ContextCompat.RECEIVER_NOT_EXPORTED 来注册它。这允许接收器监听来自其他应用程序和 Android 系统的广播。
使用
ContextCompat.registerReceiver(this, receiver, IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED), ContextCompat.RECEIVER_EXPORTED)
而不是
ContextCompat.registerReceiver(this, receiver, IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED), ContextCompat.RECEIVER_NOT_EXPORTED)