Android Activity 生命周期,重启应用而不是重启 activity

Android Activity lifecycle, restarting app instead of restart activity

我最近开发了一个 Android 应用程序。一切顺利,直到我按下设备上的主页键。 在我的一台设备(有更多内存)上,activity 恢复到正确状态并且我的应用程序运行良好。但是在其他设备上,activity 会在几秒钟后终止,当我恢复应用程序时,它会重新启动我保留默认值的 activity(不正确的行为)。 我如何强制应用程序从 main activity 重新启动应用程序而不是使用默认值重新启动此 activity?

尝试在 Manifest.xml 中为 activity 设置 android:alwaysRetainTaskState="true" 根据文档

Whether or not the state of the task that the activity is in will always be maintained by the system — "true" if it will be, and "false" if the system is allowed to reset the task to its initial state in certain situations. The default value is "false". This attribute is meaningful only for the root activity of a task; it's ignored for all other activities. Normally, the system clears a task (removes all activities from the stack above the root activity) in certain situations when the user re-selects that task from the home screen. Typically, this is done if the user hasn't visited the task for a certain amount of time, such as 30 minutes.

However, when this attribute is "true", users will always return to the task in its last state, regardless of how they get there. This is useful, for example, in an application like the web browser where there is a lot of state (such as multiple open tabs) that users would not like to lose.

更多参考click here

如果你使用android:clearTaskOnLaunch="true",完整的backstack将被清除。 您的应用程序将从头开始,这意味着应用程序主 activity 将启动,如果您不存储数据,您将以默认值结束。

终于得到答案:

我们必须在 onCreate() 的 main activity 中设置一个全局静态变量,如果该变量在我们离开应用程序的 activity 中被重置为 null,则完成!