Android中实现BLE char-write-req开启通知,onCharacteristicChanged未触发求助
Android实现与gatttool
char-write-req 0x16 01:00 相同的BLE通知设置操作 当然可以!你同事用gatttool执行的char-write-req 0x16 01:00本质是向BLE设备的客户端特征配置描述符(CCCD)写入启用通知的指令,这在Android中完全可以通过BLE API实现。下面是具体步骤和代码示例:
先理解gatttool命令的含义
char-write-req 0x16 01:00 中:
0x16是目标特征的句柄(Handle)01:00是写入的值,对应BLE标准CCCD的启用通知指令(16位小端格式,低字节0x01表示开启通知,高字节0x00表示关闭指示)
Android中的实现步骤
1. 找到目标特征及其CCCD描述符
首先需要通过BLE连接获取到目标服务、特征,然后找到该特征对应的标准CCCD描述符(UUID固定为 00002902-0000-1000-8000-00805f9b34fb):
// 替换为你的服务UUID和特征UUID BluetoothGattService targetService = gatt.getService(UUID.fromString("YOUR_SERVICE_UUID")); BluetoothGattCharacteristic targetChar = targetService.getCharacteristic(UUID.fromString("YOUR_CHARACTERISTIC_UUID")); // 获取标准CCCD描述符 BluetoothGattDescriptor cccdDescriptor = targetChar.getDescriptor( UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
2. 配置并写入CCCD值
将CCCD的值设置为01:00(对应启用通知),然后调用writeDescriptor发送请求:
// 直接使用系统提供的常量,等价于字节数组 {0x01, 0x00} cccdDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); // 发送写入请求 gatt.writeDescriptor(cccdDescriptor);
3. 启用本地通知监听
别忘告诉Android系统要监听该特征的变化,调用setCharacteristicNotification:
gatt.setCharacteristicNotification(targetChar, true);
关键注意事项
- 权限检查:Android 12+ 需要申请
BLUETOOTH_CONNECT和BLUETOOTH_SCAN权限;低版本需要BLUETOOTH和BLUETOOTH_ADMIN权限,同时确保位置权限(部分设备要求)已授予。 - 回调确认:在
BluetoothGattCallback的onDescriptorWrite方法中确认写入是否成功:@Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { super.onDescriptorWrite(gatt, descriptor, status); if (status == BluetoothGatt.GATT_SUCCESS) { Log.d("BLE", "CCCD写入成功,已启用通知"); } else { Log.e("BLE", "CCCD写入失败,状态码:" + status); } } - 设备兼容性:少数设备可能要求写入
00:01(大端格式),如果01:00无效,可以尝试替换为BluetoothGattDescriptor.ENABLE_INDICATION_VALUE(对应02:00,启用指示)或者自定义字节数组{0x00, 0x01}。 - 连接稳定性:确保BLE连接未断开,操作前检查
gatt实例是否有效。
如果执行完以上步骤onCharacteristicChanged仍未触发,建议用nRF Connect工具测试设备是否真的会在写入CCCD后发送通知,排除设备端的问题。
内容的提问来源于stack exchange,提问作者FishingIsLife
相关产品推荐
相关产品推荐

