当我在 android 中杀死或从我最近的应用程序中删除时,我需要停止我在我的应用程序中使用的所有服务。有没有可能确定?
最佳答案
服务类有一个 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();
}
然后有一个异常(exception),如果 FLAG_STOP_WITH_TASK标志被使用,这个回调不会被触发,但服务会在应用程序被杀死时自动停止。如果您需要在 Service
中执行某些操作,然后最终停止它,您可能需要使用 onTaskRemoved()
。
关于android - 我需要在我杀死或从 Android 中最近的应用程序中停止我的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43134937/