我的蓝牙GattCallback() onCharacteristicChanged在Android 13以下不起作用



我正试图用BLE设备接收数据,但它不起作用。我这样配置我的onCharacteristicChanged:

@SuppressLint("MissingPermission")
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
bluetoothGatt.requestMtu(517)
}
override fun onMtuChanged(gatt: BluetoothGatt, mtu: Int, status: Int) {
val characteristic = findCharacteristics()
enableNotification(characteristic)
}
fun ByteArray.toHexString(): String =
joinToString(separator = "", prefix = "") { String.format("%02X", it) }
override fun onCharacteristicChanged(
gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic,
value: ByteArray
) {
Log.d("CHAR", value.toHexString())
}

仅在Android 13中工作,当我在Android 11中运行应用程序时,onCharacteristicChanged不会触发。我检查的权限:

private fun checkPermissions() {
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
requestPermissions.launch(
arrayOf(
Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.BLUETOOTH_CONNECT
)
)
}
Build.VERSION.SDK_INT < Build.VERSION_CODES.S -> {
requestPermissions.launch(
arrayOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
)
)
}
}
}
private val requestPermissions =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
permissions.forEach { (key, value) ->
when (key) {
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION -> {
if (!value) {
ActivityCompat.requestPermissions(
requireActivity(),
arrayOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
),
1
)
}
}
Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT -> {
if (!value) {
ActivityCompat.requestPermissions(
requireActivity(),
arrayOf(
Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.BLUETOOTH_CONNECT
),
1
)
}
}
}
}
}

当它在Android 11上运行时,日志表明一切正常:

D/BluetoothGatt: onConnectionUpdated() - Device=7C:9E:BD:07:3D:82 interval=6 latency=0 timeout=500 status=0
D/BluetoothGatt: onSearchComplete() = Device=7C:9E:BD:07:3D:82 Status=0
D/BluetoothGatt: configureMTU() - device: 7C:9E:BD:07:3D:82 mtu: 517
D/BluetoothGatt: onConfigureMTU() - Device=7C:9E:BD:07:3D:82 mtu=517 status=0
D/BluetoothGatt: setCharacteristicNotification() - uuid: 00001103-0000-1000-8000-00805f9b34fb enable: true

我认为你必须使用这个回调代替:https://developer.android.com/reference/android/bluetooth/BluetoothGattCallback#onCharacteristicChanged(android.bluetooth.BluetoothGatt,%20android.bluetooth.BluetoothGattCharacteristic)。你正在尝试使用的重载,其中值作为参数传递是在Android 13中添加的,因此在旧设备上不起作用。

SOLVED

问题:

override fun onCharacteristicChanged(
gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic,
value: ByteArray
)

此版本的构造函数仅在设备版本高于android 12时调用

解决方案:

override fun onCharacteristicChanged(
gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic
)

添加旧版本,代码正常运行

最新更新