即使在调用disconnect()之后,Android BLE BluetoothGatt对象仍保持连接并触发onCharacteristicChanged()

Tem*_*age 7 android bluetooth-lowenergy gatt

我正在尝试在退出应用程序时断开特征通知.以下是我在exitCleanup()函数中的操作方法:

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

日志显示: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) );
}
Run Code Online (Sandbox Code Playgroud)

这是事情变得奇怪的地方.日志现在显示以下内容:FINISHING. Connection state=2,表示BluetoothDevice仍然连接.

这是一个问题,因为当应用程序完成并销毁所有资产时,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()
Run Code Online (Sandbox Code Playgroud)

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

D/BluetoothGatt? onNotify() - Device=54:4A:16:26:A1:B5 UUID=0000ffe1-0000-1000-8000-00805f9b34fb
Run Code Online (Sandbox Code Playgroud)

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

郑松岚*_*郑松岚 1

看来你不能一起调用这些方法。断开连接回调可能会晚于 close() 方法执行的时间到达。

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

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