1

我正在开发 BLE 设备。- 我可以使用BluetoothGATT将此设备与应用程序连接 - 只要与 BluetoothGatt 连接,我就能够第一次读取所有服务、特征和广告商数据。- 我们有两个特征,一个是我们需要阅读,另一个是写作,我可以写特征。

但是问题是我在写入后无法读取特征。据我了解

        @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic characteristic)

或者

        @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic characteristic,
                                     int status)

应该自动调用,这些都是Callback方法

我的特征写入代码是

boolean status = mBluetoothGatt.setCharacteristicNotification(characteristic, state);

我还通过以下代码启用通知

        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

写完后我被困在阅读特征部分

任何帮助都值得赞赏,亲爱的,在此先感谢,我在这一点上被困了 3 天。

4

1 回答 1

2

onCharacteristicRead() 和 onCharacteristicChanged()不会自动调用。

onCharacteristicRead 在您调用特性.getValue() 时触发。像这样的东西:

BluetoothGattCharacteristic charac = ... ;
byte[] messageBytes = charac.getValue();

其中charac保存您尝试读取的特征,而messageBytes保存从特征读取的值。

一旦启用通知,就会调用 onCharacteristicChanged。看起来您没有完全启用通知。

public static String CLIENT_CONFIGURATION_DESCRIPTOR_STRING = "00002902-0000-1000-8000-00805f9b34fb";

...

            mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                    UUID.fromString(CLIENT_CONFIGURATION_DESCRIPTOR_STRING));
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            mBluetoothgatt.writeDescriptor(descriptor);

您需要添加 writeDescriptor 调用才能成功启用通知。

于 2018-07-16T01:56:10.523 回答