我有一项服务必须从几项活动中获得,每项活动都使用ServiceConnection
。Android:如何判断绑定服务何时被销毁?
每个活动在调用服务之前需要检查服务是否已被使用。所以在服务中我有一个函数(比如getCurrentId()
),它返回服务当前正在执行的细节。 然后在客户端活动,该服务建立连接:
private MyService mService = null;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
MyService.MyBinder myBinder = (MyService.MyBinder) binder;
mService = myBinder.getService();
activeId = mService.getCurrentId();
log.i(TAG, "Service bound");
}
public void onServiceDisconnected(ComponentName className) {
log.i(TAG, "Service has been killed");
mService = null;
}
};
中的按钮切换绑定到服务:
activity.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
和解除绑定:
activity.unbindService(mConnection);
我不是根本不需要拨打startService()
。
之前,我绑定到服务,我检查它是否已经生效,它在做什么:
if (mService == null)
activeId = -1;
else
activeId = mService.getCurrentId();
问题是,如果活动结合,然后从服务解除绑定,服务onDestroy()
方法被调用(我登录它来确认这一点),这很好。 但是这个不是触发器onServiceDisconnected()
。
所以mService永远不会设置为null,并且当我得到该if语句时,它愉快地继续并调用getCurrentId()
,它返回以前的任何细节。
我收集onServiceDisconnected()
只应该在服务运行的线程意外死亡时被调用,所以当服务被上一次使用unbinding的活动所销毁时,它不会被调用。
据我所知,该服务没有被重新使用,我已经记录了整个服务。
这给了我两个问题:
是否有其他的回调函数或某种方式,其中一个ServiceConnection被告知其服务已被解除绑定破坏?
如果服务已将销毁,那我该如何调用它的功能呢?或者是别的什么事情 - ServiceConnection
或Binder
以某种方式返回值而不实际调用服务?
onServiceDisconnected()也在服务被销毁时(例如,它完成了它的任务)被调用,同时活动仍然被绑定!这并非罕见。但是,当在onUnbind()之后调用onDestroy()时,不会调用onServiceDisconnected。 – Bhiefer