当我退出我的应用程序时,我正在尝试断开特征通知。下面是我在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,表示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()然后继续发布触发onCharacteristicChanged()调用的onNotify()调用,即使在应用程序已经终止之后也是如此:
D/BluetoothGatt﹕ onNotify() - Device=54:4A:16:26:A1:B5 UUID=0000ffe1-0000-1000-8000-00805f9b34fb关于如何在退出应用程序时正确断开GATT特征通知,有什么建议吗?
发布于 2015-11-09 14:07:58
看起来你不能同时调用这些方法。断开回调到达的时间可能晚于执行close()方法。
您可以在onConnectionStateChange回调中添加mGatt.close();来关闭连接。
https://stackoverflow.com/questions/29873241
复制相似问题