When the back button is being pressed and the current activity is being popped, will onDestroy
be called? It seems that it's not called for me
It seems like onStop
will be called. onPause
will be called also on screen lock or incoming calls etc.
It Seems the right way to handle activity pop will be onStop()
.
It depends. If the system is not very constrained at the moment and/or your Activity isn't taking up a whole lot of memory, onStop()
will probably be called. This allows your activity to stay in memory and come back really quickly when the user switches back to it. Later on, if the user hasn't used you activity for a while and the system needs to free up some memory, then onDestroy()
will be called.
That said, if the system is very memory constrained or you Activity was using a ton of memory, onDestroy()
might be called as soon as you push the back button and go home.
For more on the activity life-cycle, please read the documentation here.
It seems like onStop
will be called. onPause
will be called also on screen lock or incoming calls etc.
It Seems the right way to handle activity pop will be onStop()
.
From Android Developers:
There are a few scenarios in which your activity is destroyed due to normal app behavior, such as when the user presses the Back button or your activity signals its own destruction by calling finish().
onDestroy()
to be called on the current activity? –
Mf Check out this discussion on stackoverflow, answers the onDestroy question fairly well, about when it is called.
Activity OnDestroy never called?
You should put your code in the onPause and onStop, and also the onSaveInstanceState/onRestoreInstanceState.
Use the onDestroy for objects that need to be cleaned up and set to null. The memory management and garbage collection processes will periodically destroy background processes, calling onDestroy.
However, to be certain that your application releases reserved memory, take care to manually clean up your objects when they are no longer needed.
I had previously mentioned some advice about using system.gc to force onDestroy to be called.
However, system.gc cannot be trusted to force onDestroy to be called, and a developer should not rely on onDestroy being called in order to clean up memory allocation objects.
So, I have edited my answer, and removed the references to system.gc.
The article mentioned in the comment by cdeange is a good article on why it is a bad practice to rely on calling system.gc. https://mcmap.net/q/18417/-why-is-it-bad-practice-to-call-system-gc
© 2022 - 2024 — McMap. All rights reserved.