安卓蓝牙 : onCharacteristicRead works only first time

标签 android bluetooth bluetooth-lowenergy gatt android-6.0.1-marshmallow

Gatt 通信仅在第一次使用时有效。
我已经阅读了很多与此相关的问题,但没有解决方案有帮助。
整个过程:
1.重启手机
2.运行应用
3.应用程序连接到BLE设备并获取可访问的Wifi网络列表(SdkGattAttributes.WIFI_CHAR_WIFI_LIST)
到目前为止一切正常
4.重启应用
5. 应用程序连接到设备并尝试获取 wifi 列表,但从未收到 onCharacteristicRead。在此之前没有发送 writeCharacteristic
6.手机重启后应用程序可以获取wifi列表,但只能获取一次
可能有什么问题。释放一些资源还是什么?如果需要,我可以发布一些代码。
提前致谢。

最佳答案

我最终找到了解决方案,因此我将其发布在这里供其他人使用。

问题是,成功连接后,MTU 设置为 mBluetoothGatt.requestMtu(512),并且相继请求服务 mBluetoothGatt.discoverServices(),这可能会混淆 gatt。

public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        mBluetoothGatt.discoverServices();
        mBluetoothGatt.requestMtu(512);
    }
}

解决方案: 首先请求 mtu,完成后发现服务

public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        mBluetoothGatt.requestMtu(512);
    }
}
public void onMtuChanged (BluetoothGatt gatt, int mtu, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        mBluetoothGatt.discoverServices();
    }
}

关于安卓蓝牙 : onCharacteristicRead works only first time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53085417/

相关文章:

android - EditText 中的光标位置

algorithm - 返回输入范围固定值的函数/算法

iphone - iPhone sdk 支持 l2cap 蓝牙 socket 吗?

android - 如何在android中通过蓝牙向配对设备发送短信?

php - Google geocode API 不返回某些位置的结果

android - apktool 没有生成 apk 文件

android - Cordova FileTransfer 下载错误

ios - AirLocate 和 BeaconDemo : not showing up

android - 当 BLE 设备向 Android 手机发送数据时,如果应用程序未运行,如何在应用程序中获得通知

c# - 如何配置 WPF 项目以使用 BLE?