如何从最近的菜单关闭应用程序时销毁 activity?

How to destroy activity when the app is closed from the recent menu?

我正在尝试在用户关闭应用程序时清除共享首选项,并且仅在他关闭应用程序时清除。使用 onDestroy() 仅在使用后退键关闭应用程序时有效,但在按下主页按钮并从最近关闭应用程序时无效。我该怎么做?

不保证一定会调用 onDestroy。我建议从各种来源阅读有关 android activity 生命周期的信息。 Android 开发人员文档未提供所有详细信息。另请查看此问题,它可能会回答您的问题 Which activity is called when app removed from recent list in android?

查看此内容以大致了解生命周期 Android activity life cycle - what are all these methods for?

尤其是在

我没有从想要清除的地方清除 activity 中的首选项,而是创建了一个 class 并在其中放置了方法 setBoolean()、getBoolean()、clearPreference(),并添加了一个 SharedPreference 编辑器。我在我的 activity 和 MainActivity 中调用 set boolean 和 get boolean,我调用 clear preferences。这样当我从最近关闭应用程序时它就可以工作了。