我需要停止我在我的应用程序中使用的所有服务,当我从我最近的Android应用程序中删除或删除时。有没有可能确定?
答案 0 :(得分:2)
Service类具有onTaskRemoved()方法,该方法会在从最近的应用中删除应用时触发。
服务可以致电stopSelf()关闭自己。
如:
/**
* This is called if the service is currently running and the user has
* removed a task that comes from the service's application. If you have
* set {@link ServiceInfo#FLAG_STOP_WITH_TASK ServiceInfo.FLAG_STOP_WITH_TASK}
* then you will not receive this callback; instead, the service will simply
* be stopped.
*
* @param rootIntent The original root Intent that was used to launch
* the task that is being removed.
*/
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
stopSelf();
}
然后有一个例外,即如果使用FLAG_STOP_WITH_TASK标志,则不会触发此回调,但是当应用程序被终止时,服务会自动停止。如果您需要在最终停止之前在onTaskRemoved()
中执行某些操作,则可能需要使用Service
。