I'm confused why anyone would ever override Activity.onDestroy()
instead of onPause()
if according to the documentation:
There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it,
I see much code that overrides onDestroy()
despite this warning. Why?
Why override Activity.onDestroy() if it isn't reliably called?
It's not that it isn't reliably called... it's just that it isn't the only way the Activity
can be killed. The Android system might trash your entire process without giving the ActivityManager
the chance to call onDestroy()
if your device begins to lack memory resources.
For this reason, you shouldn't ever rely on onDestroy()
being called, and you should always save persistent state in onPause
.
Objects held by the activity will get destroyed if the process is killed directly. If the process is not killed (and onDestroy()
is called) then you will have to manually release the objects if needed. E.g, when the process is killed, a Cursor will be destroyed, but if the process is not destroyed and you repeatedly enter the activity there will be resource leakage.
来源:https://stackoverflow.com/questions/11858200/why-override-activity-ondestroy-if-it-isnt-reliably-called