Android端BLE无法触发onCharacteristicChanged()问题求助
BLE通知不触发Android onCharacteristicChanged()的解决建议
一、修复Android端描述符设置问题
你的Android代码中存在重复设置描述符值的错误,后设置的ENABLE_INDICATION_VALUE会覆盖之前的ENABLE_NOTIFICATION_VALUE,而你的BLE特征声明的是notify属性,应对应使用通知值:
// 原错误代码 descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE); // 修改为只设置对应的值 descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
同时,不要遍历所有描述符,只针对**CCCD描述符(UUID: 00002902-0000-1000-8000-00805f9b34fb)**进行操作,避免修改无关描述符:
for (BluetoothGattDescriptor descriptor : descriptors) { Log.d(TAG, "Descriptor: " + descriptor.getUuid().toString()); // 只处理CCCD描述符 if (descriptor.getUuid().equals(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"))) { descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); boolean isWriteDesp = bluetoothGatt.writeDescriptor(descriptor); Log.d(TAG, "Descriptor write status: " + isWriteDesp); } }
二、修复Python-dbus服务器端通知逻辑
- 不要主动调用StartNotify():
StartNotify()是客户端发起订阅请求时,BlueZ框架自动调用的方法,服务器端无需主动调用,否则会干扰notifying状态的正确性:
def do_notify(self, value): # 移除这行代码:self.StartNotify() if not self.notifying: show_log(LOG_LEVEL.INFO, "Not notifying") return show_log(LOG_LEVEL.INFO, f"Sending message to client: {value}") self.PropertiesChanged(bluetooth_constants.GATT_CHARACTERISTIC_INTERFACE, {'Value': value}, []) show_log(LOG_LEVEL.INFO, f"Message sent to client: {value}")
- 确认GATT特征接口常量正确性:检查
bluetooth_constants.GATT_CHARACTERISTIC_INTERFACE的值是否为"org.bluez.GattCharacteristic1",这是BlueZ标准的GATT特征接口,错误的接口会导致PropertiesChanged信号无法被正确处理。
三、额外排查点
- 确认两端的特征UUID、服务UUID完全匹配,避免客户端订阅了错误的特征。
- 在Linux端查看蓝牙服务日志,执行
journalctl -u bluetooth.service -f,观察发送通知时是否有错误日志,确认服务器端是否成功发出通知信号。 - 检查Android设备的蓝牙权限,确保已授予
BLUETOOTH_CONNECT、BLUETOOTH_SCAN权限(Android 12+)。
内容的提问来源于stack exchange,提问作者Xianghui
相关产品推荐
相关产品推荐

