首页 > 解决方案 > Android BLE:onCharacteristicRead 仅在第一次工作

问题描述

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

标签: androidbluetoothbluetooth-lowenergygattandroid-6.0.1-marshmallow

解决方案


我最终找到了解决方案,所以我在这里为其他人发布。

问题是在成功连接后设置 MTUmBluetoothGatt.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();
    }
}

推荐阅读