正如mklimek已经提到的那样,onTaskRemoved()是实现此目的的方法.
我在带有由Activity启动和绑定的绑定服务的项目中使用它.这是各个部分(为安全起见,我会添加一些上下文):
活动从onCreate()调用自定义startService()和bindService()帮助器方法:
private void startService() {
Intent myServiceIntent = new Intent(this, packageName.MyService.class);
startService(myServiceIntent);
}
private void bindService() {
mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mService = MyServiceListener.Stub.asInterface(iBinder);
try {
mService.registerCallback(myServiceCallback);
mService.doSomething();
} catch (RemoteException e) {
MLog.w(TAG, "Exception on callback registration; Service has probably crashed.");
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mService = null;
}
};
if(!myServiceIsBound) {
Intent myServiceIntent = new Intent(this, packageName.MyService.class);
bindService(myServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
myServiceIsBound = true;
// service is now bound
} else {
// service has already been bound
}
}
现在,转到Service类:在onCreate()中,显示一个通知(运行后台服务需要afaik)并设置Binder:
@Override
public void onCreate() {
super.onCreate();
// Setup Binder for IPC
mBinder = new MyServiceBinder();
mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
[...display notification code...]
}
服务接口(如果有意思请告诉我,否则我将其留在此处):
private class MyServiceBinder extends MyServiceListener.Stub {
@Override
public void registerCallback(MyServiceCallback callback) throws RemoteException {
[...]
}
// further methods for the service interface...
}
我的onTaskRemoved()和其他生命周期方法如下所示:
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
// do something adequate here
}
// Lifecycle management
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_REDELIVER_INTENT;
}
// Binding
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
每当我从最近的应用程序列表中滑动“活动”时,都会调用我的onTaskRemoved().您确定未调用onTaskRemoved()方法(是否在其中放置了一些日志记录代码)?另外,请确保在其中调用super.onTaskRemoved()方法.
我们的代码看起来非常相似,除了我将ServiceConnection设置和Service绑定代码放入Activity中.您将许多这种逻辑移到了服务本身中.
我只能猜测,这可能是服务连接泄漏的问题所在,因为您的ServiceConnection是服务类的静态成员,并且您在ServiceConnection中维护对服务的引用(通过“ instance”变量) .我不确定,但是当活动终止时,似乎两个链接都没有断开.请注意,在我的代码中ServiceConnection如何成为Activity的成员,因此我将onServiceDisconnected()中对mService的引用清除为安全.也许您可以对它进行一些重构,考虑到活动终止时无法被GC引用.