Android的:如何安全地解除绑定服务绑定、安全、Android

由网友(你的爱、其实不值一提、)分享简介:我有被绑定到应用程序上下文这样的服务:I have a service which is binded to application context like this: getApplicationContext().bindService(new Intent(this, ServiceUI.class),se...

我有被绑定到应用程序上下文这样的服务:

I have a service which is binded to application context like this:

getApplicationContext().bindService(
                    new Intent(this, ServiceUI.class),
                    serviceConnection,
                    Context.BIND_AUTO_CREATE
            );

protected void onDestroy() {
            super.onDestroy();                  
            getApplicationContext().unbindService(serviceConnection);
        }

由于某种原因,只是有时应用程序上下文不与正常不过(我不能修复的那部分),在的onDestroy()我 unbindservice 这引发错误

java.lang.IllegalArgumentException: Service not registered: tools.cdevice.Devices$mainServiceConnection.

我的问题是:是否有办法 unbindservice 安全地调用或解除前检查是否已经绑定到服务

My question is: Is there a way to call unbindservice safely or check if it is already bound to a service before unbinding it?

在此先感谢。

推荐答案

试试这个:

boolean isBound = false;
...
isBound = getApplicationContext().bindService( new Intent(getApplicationContext(), ServiceUI.class), serviceConnection, Context.BIND_AUTO_CREATE );
...
if (isBound)
    getApplicationContext().unbindService(serviceConnection);

注意:

您应该使用相同的上下文绑定服务,并解除绑定的服务。如果绑定服务与 getApplicationContext(),所以你也应该使用 getApplicationContext.unbindService(..)

You should use same context for binding a service and unbinding a service. If you are binding Service with getApplicationContext() so you should also use getApplicationContext.unbindService(..)

阅读全文

相关推荐

最新文章