颠覆不是总是被称为吗? [英] Is ondestroy not always called?

查看:105
本文介绍了颠覆不是总是被称为吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在活动的onDestroy中放入了一些缓存清理代码,但是大多数情况下,除非我通过finish()明确完成了该活动,否则代码不会执行.

I have put some cache cleaning code in onDestroy of my activity but most of the time the code is not executed unless I explicitly finish the activity via finish().

仅使用finish()或系统资源不足时才调用onDestroy.因此,我需要将缓存清理代码放在哪里?如果将其放在onPause()中,并且用户返回到应用程序,则清除缓存.我实际上是将重要的临时文件存储在缓存中,不应在onPause中删除.

Just read onDestroy is called only with finish() or if the system is low on resources. So where do I need to put my cache cleaning code? If I put it in onPause() and the user goes back to the app, the cache is cleared. I am actually storing important temporary files in the cache that should not be deleted in onPause.

推荐答案

来自Android开发人员

From Android developer documentation:

受保护的void onDestroy()

protected void onDestroy ()

API级别1中已添加 毁了.发生这种情况可能是因为活动即将结束 (有人在其上称为 finish(),或因为系统暂时处于 销毁该活动实例以节省空间.你可以 使用isFinishing()方法区分这两种情况.

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.

注意:不要指望这种被称为的方法作为保存位置 数据!例如,如果活动正在编辑内容中的数据 提供者,这些编辑应在onPause()或 onSaveInstanceState(Bundle),不在这里.这种方法通常是 实施以释放与线程相关联的资源(如线程) 活动,这样被破坏的活动就不会留下这些东西 其余的应用程序仍在运行时.有 系统将简单地终止活动托管的情况 无需在其中调用此方法(或任何其他方法)进行处理 不应该用来做打算留在身边的事情 该过程消失后.

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()

这篇关于颠覆不是总是被称为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆