gpt4 book ai didi

android - ondestroy不总是被调用吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:55:29 26 4
gpt4 key购买 nike

我在 Activity 的 onDestroy 中放置了一些缓存清理代码,但大多数情况下代码不会执行,除非我通过 finish() 显式完成 Activity 。

编辑:只需阅读 onDestroy 仅在 finish() 或系统资源不足时调用。那么我需要将缓存清理代码放在哪里呢?如果我将其放入 onPause() 并且用户返回应用程序,缓存将被清除。我实际上将重要的临时文件存储在缓存中,这些文件不应在 onPause 中删除。

最佳答案

来自 Android 开发者 documentation :

protected void onDestroy ()

Added in API level 1 Perform any final cleanup before an activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

您可以将代码移动到 onPause()onStop()

关于android - ondestroy不总是被调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19608948/

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