gpt4 book ai didi

java - 在什么情况下应该重写 onDestroy()?

转载 作者:行者123 更新时间:2023-12-02 05:45:25 30 4
gpt4 key购买 nike

我正在阅读 Activity 生命周期,并阅读有关启动和销毁 Activity 的文档,链接如下: 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() 是框架在您的 Activity 关闭时调用的方法。调用它是为了允许您的 Activity 执行它可能希望执行的任何关闭操作。该方法实际上与垃圾收集没有任何关系。特别是,它与 C++ 析构函数无关(尽管它的名称如此)。

此方法使您的程序有机会执行清理资源等操作,以便它们不会污染关联的应用程序。如果您没有关闭操作要做,则无需覆盖它。基类基本上不执行任何操作。

关于java - 在什么情况下应该重写 onDestroy()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24118574/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com