关于java:在哪种情况下应该覆盖onDestroy()?

In which cases should one override onDestroy()?

我正在阅读活动生命周期,并阅读有关启动和销毁活动的文档,链接如下:http://developer.android.com/training/basics/activity-lifecycle/starting.html

以下文本来自链接:

Destroy the Activity

While the activity's first lifecycle callback is onCreate(), its very
last callback is onDestroy(). The system calls this method on your
activity as the final signal that your activity instance is being
completely removed from the system memory.

Most apps don't need to implement this method because local class
references are destroyed with the activity and your activity should
perform most cleanup during onPause() and onStop(). However, if your
activity includes background threads that you created during
onCreate() or other long-running resources that could potentially leak
memory if not properly closed, you should kill them during
onDestroy().

有人能举一个(或多个)后台线程或"其他长时间运行的资源"的例子来保证OnDestroy()重写,并解释他们如何避免常规的OnDestroy()清理?

澄清:我理解onPause()、onStop()和onDestroy()是如何工作的,这不是我要问的。我要求更深入地澄清什么可以保证压倒OnDestroy(OnDestroy))。


好吧,OnDestroy()是框架在活动关闭时调用的一个方法。调用它是为了允许您的活动执行它可能希望执行的任何关闭操作。该方法实际上与垃圾收集没有任何关系。特别是,它与C++的DestuCube(尽管它的名字)无关。

此方法使程序有机会执行清理资源之类的操作,这样它们就不会污染关联的应用程序。如果您没有要执行的关闭操作,则不需要覆盖它。基本类什么都不做。


当你不能把它放在onPause()onStop()中时,你必须把cleanUp logic放在onDestroy()中。

示例:您希望您的活动只有在完成时才能执行,即只执行一次。你不能把这个逻辑放在onStop()中,因为它在你的活动loses focusonPause()中被调用,而在你的活动goes to background中被调用。