Simplest Android Activity Lifecycle
Are you looking for this?
To further answer your question, yes, as you can plainly see from the above diagram the "simplest" (i.e. smallest number of method calls) lifecycle is indeed onCreate(); onStart(); onResume(); onPause();
.
You should also know about onSaveInstanceState()
and onRetainNonConfigurationInstance()
. These are NOT lifecycle methods.
All these methods are very well documented. Please read this documentation thoroughly.
To clarify things further, here are a couple of real-life scenarios:
- Activity is running, other activities come on top of it,
onPause
is called. System runs out of memory, callsonSaveInstanceState
, kills activity. User pressed back a few times, activity has to be re-instantiated (preferably using the data saved inonSaveInstanceState
). - Activity is running, user presses back. At this point
onPause->onDestroy
are called, without callingonSaveInstanceState
.
You should understand the essential difference between onPause
and onSaveInstanceState
. The former is always called, while the latter is only called when the activity instance might be re-instantiated in the future. Following this train of thought, your users will expect two things:
- When they navigate away from your Activity and later come back to it, they want it in the exact same instance that they left it (this would be achieved using
onSaveInstanceState
). They don't expect that if they exit your activity. However: - They will expect that data they have entered will be persisted (which will be done in
onPause
). For example, if they started composing a message, they'll expect to see it as a draft the next time they come back, even if they exited the activity.
You should understand how these methods are supposed to be used in order to get what your users expect. How you actually use them is up to you, your needs, and your app's nature.
Android system is handling the lifecycle: i.e. instantiating activities and calling lifecycle methods. So I don't know what you mean by "destroy the activity". You, as a developer, have no such ability.
Second, activity lifecycle flow can be sometimes confusing (I know I struggled with it at the beginning). So, just implement all lifecycle methods and put logging statements in them. Then try all real-life use cases (including receiving a call during app use) to see how lifecycle methods are called.