为什么在切换到另一个应用程序时会调用 onDestroy()

why is onDestroy() called when switching to another app

好的,我已经阅读了section on the activity lifecycle,但有些东西我还是不明白。为什么在我的应用程序中调用 onDestroy(),当我切换到在我的 phone 上运行的另一个应用程序时,或者当我按下主页按钮时。

据我了解,当应用程序失去焦点时会调用 onPause()

The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed); it indicates that the activity is no longer in the foreground (though it may still be visible if the user is in multi-window mode). Use the onPause() method to pause or adjust operations that should not continue (or should continue in moderation) while the Activity is in the Paused state, and that you expect to resume shortly.

OnStop() 我也明白了:

When your activity is no longer visible to the user, it has entered the Stopped state, and the system invokes the onStop() callback. This may occur, for example, when a newly launched activity covers the entire screen. The system may also call onStop() when the activity has finished running, and is about to be terminated.

但是,我不明白为什么 onDestroy() 也会被调用。

onDestroy() is called before the activity is destroyed. The system invokes this callback either because: 1) the activity is finishing (due to the user completely dismissing the activity or due to finish() being called on the activity), or 2) the system is temporarily destroying the activity due to a configuration change (such as device rotation or multi-window mode).

首先,我没有完成我的应用程序,也没有调用 finish()。其次,据我所知没有配置更改。

希望有人能提供帮助。

仅供参考: 我的应用程序扩展 Activity,使用多个 Threads,有一个 class 扩展 SurfaceView 并实现SurfaceHolder.Callback,使用一个 IntentService 和一个 ContentProvider。除此之外,没什么特别的。

PS: 当我关闭屏幕时,onDestroy() 没有被调用。

PPS: 我不是在寻找臭味解决方法。我想了解发生了什么以及为什么。

我不确定这是否有帮助,但据我所知,当 Android 运行 内存不足时,它会自动 运行 任何 Activity 在屏幕上不可见。

事实证明,我在我的清单中使用了 android:noHistory 标志。谢谢 this post,我能够解决我的问题。谢谢@Alexis Contour!