android - 在 BLE Android 中写入后无法获得读取特性

标签 android bluetooth bluetooth-lowenergy bluetooth-gatt

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

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

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

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

应该是自动调用的,这些是

的回调方法

我的特征写代码是

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

我也通过下面的代码启用通知

        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

写完后卡在阅读特征部分

任何可理解的帮助,提前感谢亲爱的,我在这一点上被困了 3 天。

最佳答案

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

onCharacteristicRead 在您调用 characteristic.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 调用才能成功启用通知。

关于android - 在 BLE Android 中写入后无法获得读取特性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51350910/

相关文章:

android - 如何使用样式更改所选项目的颜色?

android - 如何一次读取已连接的多个设备的 RSSI 值?

ios - 如何在应用程序未运行(终止/终止)时保持 Core Location 和 Core Bluetooth 运行?

Windows 8.1 低功耗蓝牙行为

android - 沿 RelativeLayout 底部对齐未知高度图像

android - 我如何在 Android 上获取 GPS 定位状态 - 现在(不使用监听器)

Android 通过蓝牙发送命令失败

java - 如何使用parcelable将线程类对象从一个 Activity 传递到另一个 Activity

javascript - 是否可以将多个 BLE 设备连接到一个中央设备?

java - Android:为什么在此部分中定义小部件(即MainActivity)会导致错误