第二百九十二回:Android中的BLE开发:注册特征值通知一

第二百九十二回:Android中的BLE开发:注册特征值通知一
最新回答
黄色的月亮

2026-01-29 23:01:53

在Android中进行BLE(低功耗蓝牙)开发时,注册特征值通知是客户端监听服务端特征值变化的关键步骤。以下是详细的实现方法和注意事项:

核心步骤
  1. 获取服务与特征值在注册通知前,需通过BluetoothGatt获取目标服务和特征值(参考上一章回的getServices()方法)。例如:

    BluetoothGattService service = bluetoothGatt.getService(SERVICE_UUID);BluetoothGattCharacteristic characteristic = service.getCharacteristic(CHARACTERISTIC_UUID);
  2. 启用特征值通知使用setCharacteristicNotification()方法启用通知,并设置特征值的描述符(Descriptor)以允许通知:

    // 启用特征值通知bluetoothGatt.setCharacteristicNotification(characteristic, true);// 设置描述符(通常为CLIENT_CHARACTERISTIC_CONFIG)BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID);descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);bluetoothGatt.writeDescriptor(descriptor);
  3. 监听回调方法在BluetoothGattCallback中重写onCharacteristicChanged(),处理服务端特征值变化:

    @Overridepublic void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { byte[] data = characteristic.getValue(); // 解析数据并处理}
关键注意事项
  • 描述符配置必须正确设置CLIENT_CHARACTERISTIC_CONFIG描述符(UUID: 00002902-0000-1000-8000-00805f9b34fb),否则通知可能无法生效。

  • 异步操作writeDescriptor()是异步操作,需在onDescriptorWrite()回调中确认是否成功。

  • 多特征值监听若需监听多个特征值,需为每个特征值重复上述步骤。

  • 性能优化避免频繁注册/取消通知,建议在连接建立后一次性配置所有需要的通知。

完整代码示例// 1. 获取特征值BluetoothGattService service = bluetoothGatt.getService(UUID.fromString("0000180a-0000-1000-8000-00805f9b34fb"));BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("00002a29-0000-1000-8000-00805f9b34fb"));// 2. 启用通知bluetoothGatt.setCharacteristicNotification(characteristic, true);// 3. 配置描述符BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);bluetoothGatt.writeDescriptor(descriptor);// 4. 回调处理private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() { @Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { Log.d("BLE", "Descriptor written, notifications enabled"); } } @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { byte[] data = characteristic.getValue(); Log.d("BLE", "Data received: " + Arrays.toString(data)); }};常见问题
  • 通知未触发检查描述符是否正确设置,或服务端是否支持通知(查看特征值的properties是否包含PROPERTY_NOTIFY)。

  • 连接断开确保在onConnectionStateChange()中处理连接状态,必要时重连。

  • Android版本差异部分旧版本Android可能需要额外权限或处理兼容性问题。

通过以上步骤,客户端即可实时监听服务端特征值的变化,实现双向通信。下一章回将介绍如何写入特征值数据,敬请期待!