简体   繁体   中英

Android onDestroy and Onstop not guarantied to be called

In my android app (written in kotlin) I would like to do some data saving when my activity is destroyed. But I have a problem. I've done researching and found out that onDestroy() and onStop() methods are not guarantied to be called. So practically my activity can be destroyed without calling onDestroy() method which would be disaster for me. Please, does anyone have some gentle solution for this problem?

You are right about onDestroy()

do not count on this method being called as a place for saving data!

For saving state you should use onPause() , onSaveInstanceState() or onStop() - which gets called as soon your Activity is no longer visible to the user.

Some additional information:

The purpose of overriding onDestroy is if you need to clean up leakable resources, like something that uses native memory or a spawned Thread that is holding onto object references. It will never "become safe" like you suggested in the comments because using it as a hook for saving state is not its purpose. The reason it is not guaranteed to be called is that if the OS is shutting down your application completely, the entire heap of memory for your app is released, in which case it would be redundant to call it.

The majority of apps should never need to override it because most apps don't allocate memory directly, and there are better techniques for handling asynchronous work than spawning Threads directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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