当我杀死或从 Android 中最近的应用程序中删除时,我需要停止我的服务

Sun*_*y J 3 android kill-process

当我在 Android 中杀死或删除最近的应用程序时,我需要停止我在应用程序中使用的所有服务。有没有可能确定?

Mar*_*nen 6

Service 类有一个onTaskRemoved() method which is triggered when the app is removed from the recent apps.

服务可以调用stopSelf() to shut itself down.

如:

/**
 * 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();
}
Run Code Online (Sandbox Code Playgroud)

还有一个例外,如果使用FLAG_STOP_WITH_TASK标志,则不会触发此回调,但当应用程序被终止时,服务会自动停止。onTaskRemoved()如果您需要在Service最终停止之前执行某些操作,您可能需要使用它。