android 中是否有一种方法可以知道系统何时会终止我的应用程序?

Is there a method inside android to know when the system is going to kill my app?

我们有一个应用程序很难重现的问题。使用案例如下:

我试图通过 Application class 方法 onTrimMemory()onLowMemory() 使用控制台日志,但是这些方法没有被调用。有什么方法或回调可以让我知道什么时候 android 系统会因为打开了更多的应用程序而终止我的应用程序,在这种情况下我需要做些什么吗?

您可以在 onSaveInstanceState() 中保存您需要的任何状态,并在 onRestoreInstanceState() 中恢复它们。 onDestroy() 是系统最常调用的,当你的应用程序在后台时,系统会调用它来清理空间,但不能保证调用它,所以最好已经将你的状态保存在 onSaveInstanceState() 中。

Is there any method or callback I can be listening to know when android system will kill my app due to many more apps being opened and in that case for me to do something?

不是真的。根据情况,将调用 onDestroy() 的 运行 项活动和服务。

We have one very difficult to reproduce problem with an app

这应该可以在几秒钟内重现:

  1. 运行 你的应用。

  2. 切换到另一个应用。

  3. 从您的 IDE 终止您的应用进程(例如,"Android Monitor" 工具 window 中的 "Terminate Application" 工具栏按钮)。

  4. 尝试从概览屏幕(a.k.a., 最近任务列表)返回您的应用