首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android BLE disconnect对象保持连接并触发onCharacteristicChanged(),即使在调用disconnect()之后也是如此

Android BLE disconnect对象保持连接并触发onCharacteristicChanged(),即使在调用disconnect()之后也是如此
EN

Stack Overflow用户
提问于 2015-04-26 11:04:48
回答 1查看 1.6K关注 0票数 7

当我退出我的应用程序时,我正在尝试断开特征通知。下面是我在exitCleanup()函数中的实现方法:

代码语言:javascript
复制
if (btGatt != null && mWriteChar != null) {
   boolean b=btGatt.setCharacteristicNotification(mWriteChar, false);
   Log.w("AppInfo", "Exiting and Unsubscribing: " + b);
}

日志显示:Exiting and Unsubscribing: true。到目前一切尚好。然后,我尝试使用以下命令完全断开GATT对象:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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()调用,即使在应用程序已经终止之后也是如此:

代码语言:javascript
复制
D/BluetoothGatt﹕ onNotify() - Device=54:4A:16:26:A1:B5 UUID=0000ffe1-0000-1000-8000-00805f9b34fb

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

EN

回答 1

Stack Overflow用户

发布于 2015-11-09 14:07:58

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

您可以在onConnectionStateChange回调中添加mGatt.close();来关闭连接。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29873241

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档