Comment on page
3.6 Activity Lifecycle
We’re taking a step back here and returning to our good friend the
In general, we have dealt a lot with the built in
onCreate(…)method of an activity, which is the first method that is called when an activity is launched. But as the user navigates through, out of, and back to the app, the
Activityinstances transition through many different stages in their lifecycles.
Activityclass provides a number of callbacks that allow the activity to know that a state has changed: creating, stopping, or resuming an activity; or destroying the process in which the activity resides. There are five built-in callbacks that we will investigate (among others), and you can override any of these methods to execute certain tasks at different points in the lifecycle:
This callback must be implemented, and is fired when the system first creates the activity. Here, you perform basic application startup logic that should happen only once for the entire life of the activity (such as instantiation of class variables, loading data in from the network, etc.). Upon completing this method invokes
This is the stage in the lifecycle when the activity becomes visible to the user (and initializes the UI code). The method completes very quickly, and invokes the
This method is called when the app officially begins “running” and comes to the foreground. The resumed state of the app is when the app interacts with the user.
The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed). It indicates that the activity is no longer in the foreground (though it may still be visible if the user is in multi-window mode).
This method is used to pause or adjust operations that should not continue when the app is in the paused state.
This method gets called when an activity is no longer visible to the user.
This method is called right before the application is destroyed. This can either be a temporary destruction and re-creation (like the user rotating their phone), or because the Activity is finishing, which is caused either through the
finish()method or the user manually dismissing the Activity.
The following diagram gives a quick summary of all lifecycle methods and their relationships to one another.
Diagram of Android lifecycle events
Although knowing these different lifecycle methods and what each one does is quite good for coding interviews, being able to use an
onCreate()method is sufficient for 95% of building activities. For now, just know that there do exist ways of performing different actions at specific points in an application’s lifecycle.