android - 尝试取消绑定服务时出现“服务未注册”错误
问题描述
我有一个服务接收器来处理与 BLE GATT 事件(连接、断开连接等)相关的回调。
在我杀死 BLE 设备以模拟丢失的情况下,断开连接事件会触发,并且我的调用context.unbindService(serviceConnection)
失败。我检查了一些明显的错误(不同的上下文、空服务连接等),但找不到错误。为什么我会收到此异常?
这是跟踪:
E/AndroidRuntime:致命异常:主进程:com.example.ktest,PID:6372 java.lang.IllegalArgumentException:服务未注册:com.example.ktest.ble.BLEConnectionManager$serviceConnection$1@493960 at android.app.LoadedApk。 com.example.ktest.ble.BLEConnectionManager.unBindService 上 android.content.ContextWrapper.unbindService(ContextWrapper.java:717) 上 android.app.ContextImpl.unbindService(ContextImpl.java:1710) 上的 forgetServiceDispatcher(LoadedApk.java:1602) (BLEConnectionManager.kt:81) 在 com.example.ktest.foo.FooActivity.disconnect(FooActivity.kt:268) 在 com.example.ktest.foo.FooActivity.access$disconnect(FooActivity.kt:47) 在 com。 example.ktest.foo.FooActivity$gattUpdateReceiver$1$onReceive$1.run(FooActivity.kt:190) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handler.dispatchMessage(Handler.java: 99)在机器人。os.Looper.loop(Looper.java:193) 在 android.app.ActivityThread.main(ActivityThread.java:6863) 在 java.lang.reflect.Method.invoke(Native Method) 在 com.android.internal.os。 RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
这是根据跟踪调用的断开功能:
private fun disconnect() {
BLEConnectionManager.unBindService(this@FooActivity) // FAILS HERE
unregisterServiceReceiver()
val intent = Intent(this, ConnectDeviceActivity::class.java)
startActivity(intent)
finish() // close activity
}
该服务使用相同的上下文绑定(来自FooActivity.onStart()
):
BLEConnectionManager.bindService(this@FooActivity)
所以BLEConnectionManager.bindService()
调用时没有问题:
fun bindService(context: Context) {
if (serviceConnection != null && isBound) {
Log.w(TAG, "Service is already bound")
} else {
val gattServiceIntent = Intent(context, BLEService::class.java)
if (context != null) {
isBound = context.bindService(
gattServiceIntent,
serviceConnection,
Context.BIND_AUTO_CREATE)
}
Log.i(TAG, "BLEService now bound, isBound is now $isBound")
}
}
这是BLEConnectionManager.unBindService()
fun unBindService(context: Context) {
// NOTE I've logged the service and connection here, they're non-null and BLE works fine in this Activity
if (serviceConnection != null && isBound) context.unbindService(serviceConnection)
}
那么我错过了什么,我做错了什么导致异常?
解决方案
我调用 unbind 的次数太多(在以前未绑定且此后未再次绑定的服务上)。这是因为我忘记isBound
在该类的 unbind 方法中设置我的 BLEConnectionManager 标志。哎呀。
推荐阅读
- javascript - 限制 SharePoint 新表单项上的 Java 附件数?
- javascript - 如何禁用数组和对象的 Chrome JavaScript 控制台重新评估?
- oauth-2.0 - Acumatica 报告创作和单点登录
- javascript - Style.visibility 不隐藏元素
- angular - 茉莉花,业力,正确地嘲笑一个承诺
- xamarin - 在 ZXing 上缩放或增强性能
- python - Keras 变分自动编码器示例 - 潜在输入的使用
- javascript - Javascript切片日期/时间带前导零
- bootstrap-4 - Bootstrap 4.1 模式在 IE11 中调整输入焦点的大小
- c - 无法使用 libtirpc 构建 RPC 项目