【问题标题】:Android BLE: onCharacteristicRead works only first timeAndroid BLE:onCharacteristicRead 仅在第一次工作
【发布时间】:2018-10-31 14:13:17
【问题描述】:

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

【问题讨论】:

  • 我有一个类似的问题,我会连接到一个设备,调用一个特性,然后不断开连接。然后我会尝试另一个连接,但无法从相同的特征中获取我的数据。解决方案是在我对特征进行读取或写入操作后显式断开连接
  • 感谢您的努力,但没有帮助。

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果需要,不要忘记在onCharacteristicWriteRequest 中发送回复:

    if (responseNeeded) {
                bluetoothGattServer?.sendResponse(device,
                        requestId,
                        BluetoothGatt.GATT_SUCCESS,
                        offset,
                        value)
            }
    

    还有一种可能,如果你发送的数据没有一次收到(preparedWrite为真,有特定的偏移量),你需要在数据完全收到后在onExecuteWrite上处理并发送响应。

    bluetoothGattServer?.sendResponse(device,
                    requestId,
                    BluetoothGatt.GATT_SUCCESS,
                    0,
                    ByteArray(0))
    

    【讨论】:

    • 感谢您的努力,但没有帮助。
    猜你喜欢
    • 1970-01-01
    • 2016-02-17
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多