简体   繁体   English

ondestroy不总是被称为?

[英]Is ondestroy not always called?

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() . 我在我的活动的onDestroy中放了一些缓存清理代码,但大部分时间代码都没有执行,除非我通过finish()明确地完成了活动。

Edit: Just read onDestroy is called only with finish() or if the system is low on resources. 编辑:只读完onDestroy只能使用finish()或系统资源不足。 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. 如果我将它放在onPause()并且用户返回应用程序,则清除缓存。 I am actually storing important temporary files in the cache that should not be deleted in onPause . 我实际上是将重要的临时文件存储在缓存中,不应该在onPause删除。

From Android developer documentation : 来自Android开发者文档

protected void onDestroy () protected void onDestroy()

Added in API level 1 Perform any final cleanup before an activity is destroyed. 在API级别1中添加在销毁活动之前执行任何最终清理。 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. 这可能是因为活动正在完成(有人称为finish() ,或者因为系统暂时销毁此活动实例以节省空间。您可以使用isFinishing()方法区分这两种情况。

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. 例如,如果某个活动正在编辑内容提供程序中的数据,那么这些编辑应该在onPause()或onSaveInstanceState(Bundle)中提交,而不是在此处。 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. 在某些情况下,系统会简单地杀死活动的托管进程,而不会在其中调用此方法(或任何其他方法),因此它不应该用于执行在进程消失后保留的内容。

You can move your code to onPause() or onStop() 您可以将代码移动到onPause()onStop()

try to use onstop 尝试使用onstop

like this 像这样

@Override
    protected void onStop() {
        super.onStop();
       //write your code here
    }

ondestroy主要在系统从内存中完全删除活动时调用,或者当用户杀死活动时,您希望在暂停时保存数据,因为在销毁之前总是会调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM