我有一个绑定到应用程序上下文的服务,如下所示:
getApplicationContext().bindService(
new Intent(this, ServiceUI.class),
serviceConnection,
Context.BIND_AUTO_CREATE
);
protected void onDestroy() {
super.onDestroy();
getApplicationContext().unbindService(serviceConnection);
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,有时只有应用程序上下文没有正确绑定(我无法修复该部分),但是在onDestroy()中我做了unbindservice哪个会抛出错误
java.lang.IllegalArgumentException: Service not registered: tools.cdevice.Devices$mainServiceConnection.
Run Code Online (Sandbox Code Playgroud)
我的问题是:unbindservice在解除绑定之前,有没有办法安全地打电话或检查它是否已绑定到服务?
提前致谢.
我想知道什么时候Context.bindService()回来false?
我已经尝试进行onBind()返回null,但是true在bindService调用时它仍然会返回并且onServiceConnected不会执行.我也在Google网上论坛上看到了此消息,但没有回复
https://groups.google.com/forum/#!topic/android-developers/ZLl56Mz1jYg
我也找不到bindService的实现,因为它在Context.java中是抽象的,并且搜索"public boolean bindService"也不会产生任何有用的结果(最接近的是ApplicationContext,它似乎不存在于当前的API级别中).
我的应用使用其他(我的)应用提供的服务.我使用的绑定的服务机智Messenger访问和与它(和,因为它是一个不同的应用程序,它也是一个远程服务)进行通信.
当我打电话bindService了适当的意图,并调用返回false(如当APK提供服务不在身边预期),我从文档和示例代码假设,那我就不需要unbind了ServiceConnection.但是,当我在我的Galaxy Nexus(Jelly Bean)设备上这样做时,我ServiceConnectionLeaked在完成时得到了众所周知的信息Activity.
我通过这样做来挽救这一点
if (!ctxt.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)) {
try {
ctxt.unbindService(serviceConnection);
} catch (Throwable t) {}
// Clean up
return;
}
// Store serviceConnection for future use
Run Code Online (Sandbox Code Playgroud)
我很好奇:我是否只是遗漏了文档中的内容,是否应该以这种方式工作?我添加了try ... catch以确保即使此行为在其他设备或Android版本上确实不同,我的应用程序也不会(负面)受其影响.