Is ondestroy not always called?

做~自己de王妃 提交于 2019-12-17 04:35:11

问题


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

Edit: 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.


回答1:


From Android developer 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.

You can move your code to onPause() or onStop()




回答2:


try to use onstop

like this

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



回答3:


ondestroy is mostly called when the system completely removes the activity from memory, or when a user kills the activity, you want to save your data in on pause, as that will always be called before the destroy.



来源:https://stackoverflow.com/questions/19608948/is-ondestroy-not-always-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!