【问题标题】:Android BLE BluetoothGatt object remains connected and triggers onCharacteristicChanged() even after a call to disconnect()即使在调用 disconnect() 之后,Android BLE BluetoothGatt 对象仍保持连接并触发 onCharacteristicChanged()
【发布时间】:2015-07-04 13:52:17
【问题描述】:

我在退出应用程序时尝试断开特征通知。这是我在 exitCleanup() 函数中的操作方式:

if (btGatt != null && mWriteChar != null) {
   boolean b=btGatt.setCharacteristicNotification(mWriteChar, false);
   Log.w("AppInfo", "Exiting and Unsubscribing: " + b);
}

日志显示:Exiting and Unsubscribing: true。到目前为止,一切都很好。 然后我尝试使用以下方法完全断开 GATT 对象:

if (btGatt != null && btManager!=null && btManager.getConnectionState(btDevice, BluetoothProfile.GATT) != BluetoothProfile.STATE_DISCONNECTED ) {
    //Making sure that gatt and bt manager are still with us
    //Also making sure that the connection state is NOT disconnected
    btGatt.disconnect();
    btGatt.close();
    Log.w( "AppInfo", "FINISHING. Connection state=" + btManager.getConnectionState(btDevice, BluetoothProfile.GATT) );
}

这就是事情变得奇怪的地方。日志现在显示以下内容:FINISHING. Connection state=2,表示蓝牙设备仍处于连接状态。

这是一个问题,因为当应用程序完成并销毁所有资产时,BluetoothGattCallback 仍然继续在后台接收通知。首先它会抛出以下 NullPointerException:

04-25 22:49:54.392  17280-17293/com.myapp.appinfo D/BluetoothGatt﹕ onClientConnectionState() - status=0 clientIf=8 device=54:4A:16:26:A1:B5
04-25 22:49:54.392  17280-17293/com.myapp.appinfo W/BluetoothGatt﹕ Unhandled exception in callback
java.lang.NullPointerException
        at android.bluetooth.BluetoothGatt$1.onClientConnectionState(BluetoothGatt.java:168)
        at android.bluetooth.IBluetoothGattCallback$Stub.onTransact(IBluetoothGattCallback.java:71)
        at android.os.Binder.execTransact(Binder.java:404)
        at dalvik.system.NativeStart.run(Native Method)
04-25 22:49:54.402  17280-17280/com.myapp.appinfo D/BluetoothManager﹕ getConnectionState()

然后继续发布触发 onCharacteristicChanged() 调用的 onNotify() 调用,即使在应用程序之前终止后也是如此:

D/BluetoothGatt﹕ onNotify() - Device=54:4A:16:26:A1:B5 UUID=0000ffe1-0000-1000-8000-00805f9b34fb

关于在退出应用程序时如何正确断开 GATT 特征通知的任何建议?

【问题讨论】:

  • 嗨,温和,我也有同样的问题。您是否能够找到解决方案?请分享。
  • 绕过此错误的唯一方法是禁用然后重新启用蓝牙设备,这是一种非常骇人听闻的方法。我仍在寻找更好的建议。
  • 在断开连接和关闭之间设置一个延迟,以消除异常

标签: android bluetooth-lowenergy gatt


【解决方案1】:

看来你不能一起调用这些方法。断开回调可能会晚于 close() 方法执行。

您可以添加 mGatt.close();进入 onConnectionStateChange 回调以关闭连接。

https://code.google.com/p/android/issues/detail?id=183108

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多