用于控制服务的防御性代码

时间:2011-10-02 19:56:41

标签: android

我正在尝试修改我的多活动应用程序,只使用一次我打算在服务中实现的LocationListener实例。在此之前,我一直在尝试使用存根活动和存根服务来查看错误条件下会发生什么。

我想看看如果我尝试从已经解除绑定的服务解除绑定并且如果发生这种情况则避免任何错误会发生什么。该活动有两个用于绑定/取消绑定的按钮。如果我故意连续两次击中unbind,我会收到运行时错误。

我可以在标记为'<<<<<<<<<在下面的代码中跳过再次调用unbind?

我的活动代码是

public void myClickHandler(View target) {
    switch (target.getId()) {
    case R.id.bind:
        Log.d("STAG", "Activity One pressed BIND button");
        mServiceConnected = bindService(new Intent(
                "com.nbt.servicetest.LOCATIONSERVICE"), mServconn,
                Context.BIND_AUTO_CREATE);
        break;
    case R.id.unbind:
        Log.d("STAG", "Activity One pressed UNBIND button");
        try{
        if (mServconn != null) // <<<< What to put here if already unbound?
            unbindService(mServconn);}
        catch(Exception e){
            Log.d("STAG", "Exception " + e.getMessage());
        }
        break;
    }
}

ServiceConnection mServconn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.d("STAG", "Activity One service connected");
        mIbinder = service;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d("STAG", "Activity One service disconnected");
    }
};

服务正在启动/停止正常。我已在所有相关行中将日志行放在服务代码中,并带有相同的标记。输出是:

STAG(2945): Activity One onCreate
STAG(2945): Activity One onStart
STAG(2945): Activity One onResume
STAG(2945): Activity One pressed BIND button
STAG(2945): Loc service ONCREATE
STAG(2945): Loc service ONBIND
STAG(2945): Activity One service connected
STAG(2945): Activity One pressed UNBIND button
STAG(2945): Loc service ONUNBIND
STAG(2945): Loc service ONDESTROY
STAG(2945): Activity One pressed UNBIND button
STAG(2945): Exception Service not registered: com.nbt.servicetest.ServiceTesterActivityOne$1@43b8b290

我注意到活动的 onServiceDisconnected()永远不会被调用,这是正常的吗?

2 个答案:

答案 0 :(得分:1)

最简单的方法是引入另一个变量,比如isServConnBound,并添加对绑定和取消绑定操作的检查。当然,请记得在致电bindServiceunbindService后更新变量。

答案 1 :(得分:1)

我同意vhallac - 只需使用布尔标志。您对此方法有何顾虑?至于我,没有什么可担心的。

至于为什么“活动的onServiceDisconnected()永远不会被调用” - 是的,这是正常的。看看API在这个回调中说了什么:

  

与服务的连接丢失时调用。这通常发生在托管服务的进程崩溃或被杀死时。

您的进程既没有崩溃也没有被杀死,所以这是预期的行为。更重要的是,由于您在同一个过程中拥有自己的服务,因此您永远不会被调用。当您绑定到在另一个进程中运行的服务(进程间通信)时,这很重要。