Android BluetoothGatt writeDescriptor弃用及onCharacteristicChanged适配问题
Android Bluetooth GATT 适配 SDK 33 最优方案
一、解决 writeDescriptor 弃用警告问题
你已经通过SDK版本分支调用新旧方法,但仍有警告,是因为Lint未识别到分支判断的有效性。只需给旧版本调用代码添加@SuppressLint("ObsoleteSdkInt")注解即可消除警告。同时推荐使用SDK33新增的带Executor的重载方法,提升回调线程可控性:
private val gattCallback = object : BluetoothGattCallback() { override fun onDescriptorWrite(gatt: BluetoothGatt?, descriptor: BluetoothGattDescriptor?, status: Int) { // 处理旧版本写入结果 } } fun writeDescriptor(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, executor: Executor) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // SDK33+ 使用新重载,指定回调线程 gatt.writeDescriptor(descriptor, executor, object : BluetoothGattCallback() { override fun onDescriptorWrite(gatt: BluetoothGatt?, descriptor: BluetoothGattDescriptor?, status: Int) { // 处理新版本写入结果,可复用旧逻辑 this@YourClass.gattCallback.onDescriptorWrite(gatt, descriptor, status) } }) } else { // 旧版本添加注解消除警告 @SuppressLint("ObsoleteSdkInt") gatt.writeDescriptor(descriptor) } }
二、onCharacteristicChanged 适配方案
SDK33新增了带直接字节参数的onCharacteristicChanged重载方法,但无需分别适配两套逻辑,最优做法是重写两个版本的回调,将处理逻辑统一到私有方法中,既兼容旧版本,又能利用新版本的便捷性:
class CustomGattCallback : BluetoothGattCallback() { // 旧版本回调(SDK33以下) override fun onCharacteristicChanged(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?) { val value = characteristic?.value handleCharacteristicUpdate(gatt, characteristic, value) } // SDK33+ 新增的回调,直接获取字节数据 @RequiresApi(Build.VERSION_CODES.TIRAMISU) override fun onCharacteristicChanged( gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, value: ByteArray? ) { handleCharacteristicUpdate(gatt, characteristic, value) } // 统一处理逻辑 private fun handleCharacteristicUpdate(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, value: ByteArray?) { // 这里编写你的业务逻辑,比如解析数据、更新UI等 } }
三、额外注意事项
- 若使用SDK33新增的Gatt方法(如带Executor的
setCharacteristicNotification),确保传入的Executor是单线程类型(如Executors.newSingleThreadExecutor()),避免多线程操作Gatt导致的异常。 - 目标SDK33需申请
BLUETOOTH_CONNECT权限,且在运行时动态申请,否则Gatt操作会失败。
内容的提问来源于stack exchange,提问作者Compose Learner
相关产品推荐
相关产品推荐

