正如 mklimek 已经提到的,onTaskRemoved()
这是实现这一目标的方法。
我在一个具有由活动启动和绑定的绑定服务的项目中使用它。以下是各个部分(为了安全起见,我将添加一些上下文):
Activity调用自定义startService()
and bindService()
辅助方法来自onCreate()
:
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()
,我显示一条通知(据悉这是运行后台服务所需的)并设置 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...
}
My 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);
}
My onTaskRemoved()
每次我从最近的应用程序列表中滑动活动时都会调用。你确定你的onTaskRemoved()
未调用方法(您是否在其中放置了一些日志记录代码)?另请务必致电super.onTaskRemoved()
里面的方法。
我们的代码看起来非常相似,只是我将 ServiceConnection 设置和服务绑定代码放入了 Activity 中。您将很多此类逻辑移至服务本身中。
我只能猜测,也许这里存在服务连接泄漏的问题,因为您的 ServiceConnection 是 Service 类的静态成员,并且您在 ServiceConnection 中维护对服务的引用(通过您的“实例”变量) 。我不确定,但当活动终止时,两个链接似乎都没有损坏。请注意,在我的代码中,ServiceConnection 是如何成为 Activity 的成员,并且我清除了对的引用mService
in onServiceDisconnected()
为了安全起见。也许您可以稍微重构一下,考虑到 Activity 终止时无法进行 GC 的引用。