Android的:如何安全地解除绑定服务 [英] Android: How to safely unbind a service

查看:359
本文介绍了Android的:如何安全地解除绑定服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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(..)

这篇关于Android的:如何安全地解除绑定服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆