When Activities Die
So, what gets rid of an activity? What can trigger the chain of events that results in onDestroy()
being called?
First and foremost, when the user presses the BACK button, the foreground activity will be destroyed, and control will return to the previous activity in the user’s navigation flow (i.e., whatever activity they were on before the now-destroyed activity came to the foreground).
You can accomplish the same thing by calling finish()
from your activity. This is mostly for cases where some other UI action would indicate that the user is done with the activity (e.g., the activity presents a list for the user to choose from — clicking on a list item might close the activity). However, please do not artificially add your own “exit”, “quit”, or other menu items or buttons to your activity — just allow the user to use normal Android navigation options, such as the BACK button.
If none of your activities are in the foreground any more, your application’s process is a candidate to be terminated to free up RAM. As noted earlier, depending on circumstances, Android may or may not call onDestroy()
in these cases (onPause()
and onStop()
would have been called when your activities left the foreground).
If the user causes the device to go through a configuration change, such as switching between portrait and landscape, Android’s default behavior is to destroy your current foreground activity and create a brand new one in its place. We will cover this more in the next chapter.
And, if your activity has an unhandled exception, your activity will be destroyed, though Android will not call any more lifecycle methods on it, as it assumes your activity is in an unstable state.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.