我正在开发一个 BLE 应用程序,基于谷歌提供的 Gatt 示例项目:https ://developer.android.com/samples/BluetoothLeGatt/index.html 。所以,我可以成功发送数据写入一个特性。现在我需要知道这个特征什么时候改变它的值。
设备活动
private void displayGattServices(List<BluetoothGattService> gattServices)
{
// get services & characteristics
................
final BluetoothGattCharacteristic characteristic = mGattCharacteristics.get(2).get(0);
final int charaProp = characteristic.getProperties();
mWriteCharacteristic = characteristic;
mBluetoothLeService.setCharacteristicNotification(mWriteCharacteristic, true);
// write in the characteristic to send a reset command to BLE device
// Start the read method, that permit subscribe to the characteristic
BluetoothLeService.read(mWriteCharacteristic);
BluetoothLeService.set(mWriteCharacteristic,true);
};
蓝牙服务
public static void read(BluetoothGattCharacteristic characteristic)
{
if (mBluetoothAdapter == null || mBluetoothGatt == null)
{
Log.w("BluetoothAdapter not initialized");
return;
};
mBluetoothGatt.readCharacteristic(characteristic);
};
public static void set(BluetoothGattCharacteristic characteristic, boolean enabled)
{
if(mBluetoothAdapter == null || mBluetoothGatt == null)
{
Log.w("BluetoothAdapter not initialized");
return;
};
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
UUID uuid = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(uuid);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
};
但我不知道如何捕捉读取特征的值。实际上,我不知道我的代码是否成功订阅了该特征。有人可以帮助我吗?如何检查特征值是否真的发生了变化?以及如何在屏幕上显示此特性的新值?我的代码是否正确,或者我需要添加、修改或删除某些内容?提前谢谢。我以这个问题为指导:Reading multiple features from a BLE device synchronously (Recommended Method for Android)