Activity 生命周期图与生命周期描述的矛盾

Contradiction in Activity lifecycle diagram versus description of lifecycle

我不清楚 activity 被 OS 变成 "destroyed" 时的情况。

让我解释一下原因 - 在此处的 activity 生命周期图中:http://developer.android.com/reference/android/app/Activity.html

有一个箭头直接从 onStop() 指向 'App process killed',然后一个箭头从 'App process killed' 指向 OnCreate()。

因此,此图显示如果 OS 由于内存限制等原因杀死 activity,则不会调用 onDestroy()

然而在生命周期的描述中多次使用"destroy"这个词。例如,此页面中的以下引用:http://developer.android.com/training/basics/activity-lifecycle/recreating.html

The system may also destroy your activity if it's currently stopped and hasn't been used in a long time or the foreground activity requires more resources so the system must shut down background processes to recover memory.

所以文档说 activity 已被销毁,但在图中箭头从 onStop() 指向 onCreate() 并绕过 onDestroy()。这就是为什么我很困惑,因为这显然是矛盾的。

如果我有一个 activity,它在它的 onCreate() 方法中创建了一些对象,我在 onDestroy() 中将它们设置为 null,但是如果应用程序从 onStop() 移动到onCreate() 那么我不会有内存泄漏,因为它们将在 onCreate() 中再次创建吗?

我不能在 onStop() 中将它们设置为空,因为如果生命周期从 onStop() 移动到 onRestart() 再到 onStart(),它们将为空。

因此,如何处理 activity 中创建和销毁子对象的正确顺序,以便处理生命周期图中的所有路径? 是否有必要在 onCreate() 中仅在对象为 null 时创建对象而不是其他情况?

This diagram therefore shows that onDestroy() is NOT called if the OS kills the activity due to memory constraints etc.

有问题的箭头标记为 "Apps with higher priority need memory"。因此,此图显示如果 the OS terminates the process 则不会调用 onDestroy(),因为优先级较高的应用程序需要内存。在其他情况下,Android 将更温和地终止应用程序进程,在这些情况下,Android 将花时间调用 onDestroy() 来处理您的活动。 onDestroy() 在其他场景中也会被调用,例如 finish()、BACK 按钮的默认行为、配置更改时的默认行为等。

If I have an activity which creates some objects in its onCreate() method and I set them to null in onDestroy() but onDestroy() is not called if the app moves from onStop() to onCreate() then won't I have a memory leak as they will get created again in onCreate()?

没有,因为整个过程都终止了"if the app moves from onStop() to onCreate()"。 Android does not destroy individual activities due to low memory conditions,尽管文档中有一些相反的说法。

Therefore how does one deal with the correct sequence of creating and destroying of child objects within an activity in order to deal with all paths in the lifecycle diagram?

很多事情应该在 onStop() 或之前清理。具体而言,您所做的任何可能导致用户后悔安装您的应用程序的操作(例如请求 GPS 修复)都应考虑在 onPause()onStop().

中进行清理

对于您认为应该在 onDestroy() 中清理的那些东西,请这样做。 AFAIK,只有三种可能:

  1. 你被叫 onDestroy() 并且可以做你的清理工作

  2. 您的进程已终止,在这种情况下,您的清理工作不再需要或不可能

  3. 您因未处理的异常而崩溃,在这种情况下 Android 不能保证调用任何更多生命周期方法(这个故事的寓意:使用良好的异常处理程序)