preface
Series of articles:
Android Activity to interact with the View of thinking Android Activity life cycle, and to monitor the Android onSaveInstanceState/onRestoreInstanceState originally to be understood What does Android Fragment want you to use?
When you write your first Android “Hello World”, you are already unknowingly dealing with the Activity life cycle. This section is one of the most basic knowledge of Android and is a frequent interview guest, as well as a foundation for understanding Jetpack components. There are numerous articles about this on the Internet, but most of them are superficial, without systematic analysis, and easy to forget after reading. This series will focus on a series of knowledge points derived from this. Through this article, you will learn:
1. What is the life cycle? Who is behind the life cycle? 3. How to perceive the life cycle
1. What is the life cycle
The name is not a term invented by computers. Anything living has a cycle, from birth to death. Take people:
This is a person’s growth trajectory, but also a person’s life cycle, different at different ages. As the saying goes: people live a lifetime, vegetation an autumn. The reincarnation of Buddhism, when a person buried in peace, assuming reincarnation, in the next reincarnation to experience birth to death, this person or the last life of that person? The same plants fade, and when they come up again in spring, will they still be what they were? No, they’re all new life.
The Activity life cycle
First look at the official image:
As an object, an Activity has a “life”, similar to people and plants. Its life cycle is its life cycle.
Why are there different stages of the life cycle? Like people:
1, when in the infant stage, every day to drink milk, nothing to cry, adults will appease you. 2, when in the student days, you seriously do, we treat you as a child, do not need you to go out to make money, attractions can give you 50% discount student tickets. When in the working era, move bricks well, the boss will give you a blessing. 4,…
Similarly, for an Activity, it does different things internally at different stages, and the external listener will take different measures at different stages. To sum up:
The stages of the life cycle are not only for the needs of circulation within the “living body”, but also to let the outside know the current stage of the “living body” and make corresponding decisions.
Like a person or plant, when an Activity goes through a life cycle, it rebuilds a different object.
Different phases of the Activity lifecycle
It is mainly divided into:
Create Destroy, Start Stop, Resume Pause Since there are callbacks for each phase, you just need to override the corresponding callback method and add print to test which phase the Activity is in after different operations.
Let’s look at some common scenarios for switching between activities:
Activity A Starts Activity B
From Activity A, press Home to return to the desktop
Return to desktop or recent task list:
Activity B Press the back key/call Finish
Activity B is at the top of the stack and Activity A is below it.
Pause phase
All of the scenarios listed above are onPause–>onStop. Is there a phase of the Activity that only stays in onPause? The Pause phase is an Activity that is visible but has no focus and therefore cannot interact with the user. Visible means it has an Activity above it, and the Activity above it is transparent, so you can see the Activity underneath. In this case, the underlying Activity is in the Pause phase.
Who is behind the life cycle?
We know that Android is event-driven and executes MessageQueue through a Loop. Are onCreate, onStart, and onStop executed in the same Message? To figure this out, you need to know the stack of callbacks to these methods. As we all know, the four components are controlled by AMS (Activity Manager Service), and AMS runs in the system_server process, which is a different process from our App. AMS communicates with each App through Binder.
Next, we’ll explore how AMS controls Activity lifecycle callbacks.
OnCreate call stack
Make a breakpoint in onCreate() and call the stack as follows:
You can see that the entry is in the ActivityThread. Java class.
1. When the App process starts, pass ApplicationThread to AMS, similar to registering a callback with AMS. 2. AMS notifies the App Activity lifecycle through ApplicationThread. 3. The App switches to the main thread to execute the corresponding method, and finally executes the Activity’s onCreate(), onStart(), onResume() and other methods.
Call stacks for other phases
Similar to onCreate, the onStart, onResume, onPause, onStop, and onDestroy phases also go through the AMS– >App– > switch to the main thread –> callback method. For convenience, the AMS process is omitted and shown as follows:
From the above analysis, it can be seen that:
1. AMS is behind the Activity life cycle. 2. The call stack for each phase is similar, but the method name has been changed. OnCreate, onStart, and onStop are not executed in the same Message, but are executed in the main thread.
3. How to perceive the life cycle
Register to monitor
Knowing the ins and outs of the lifecycle, it is easy to listen for the lifecycle by overriding the callback method for the corresponding phase in the Activity, which is our most basic choice. Now there is a requirement: is the listening App in the foreground or background? If the Activity is in the background, it will be stopped. If it goes back to the foreground, it will go through the Start phase, recording +1 when it enters the Start phase and -1 when it enters the Stop phase. If the final result record =1, it indicates that App is in the foreground. In this sense, we need a common Activity to keep a unified record from which every new Activity inherits. This satisfies our needs, but it has its drawbacks: it’s a lot of work, and it’s inflexible. There are actually better ways to listen globally to each Activity lifecycle.
#Application.java public void registerActivityLifecycleCallbacks(ActivityLifecycleCallbacks callback) { synchronized (mActivityLifecycleCallbacks) { mActivityLifecycleCallbacks.add(callback); }}Copy the code
Application. There is a method in Java, just as its name implies is used to register the Activity lifecycle callback, the callback will be added to the callback List: mActivityLifecycleCallbacks. First look at ActivityLifecycleCallbacks form:
It is an interface, at first glance, there are many methods, in fact, there are rules to follow, summed up is listening:
Create, Start, Resume, Pause, Stop, Destroy, SaveInstanceState
Callbacks at various stages. And each stage is divided into three sub-stages:
Before, during, and after this phase
For the Create phase, three callback methods are defined:
# Application. Java public interface ActivityLifecycleCallbacks {/ / default before the Create phase void onActivityPreCreated(@android.annotation.NonNull Activity activity, @ android. The annotation. Nullable Bundle savedInstanceState) {} / / the Create phase of void onActivityCreated(@android.annotation.NonNull Activity activity, @android.annotation.Nullable Bundle savedInstanceState); / / the Create phase after the default void onActivityPostCreated (@ android. The annotation. NonNull Activity to Activity, @android.annotation.Nullable Bundle savedInstanceState) { } //... }Copy the code
Only methods in the current phase must implement the class implementation; the other two methods are default.
Lifecycle callback principle
Once the listener is registered, examine how the callback is invoked. Since you are listening for the Activity lifecycle, you should start with activity.java. Remember the Activity callback stack we analyzed earlier, again using onCreate as an example:
#Activity.java protected void onCreate(@android.annotation.Nullable Bundle savedInstanceState) { ... mFragments.dispatchCreate(); / / distribute dispatchActivityCreated (savedInstanceState); . } private void dispatchActivityCreated (@ android. The annotation. Nullable Bundle savedInstanceState) {/ / call the method in the Application getApplication().dispatchActivityCreated(this, savedInstanceState); }Copy the code
The implementation in application.java is as follows:
#Application.java void dispatchActivityCreated(@android.annotation.NonNull Activity activity, @ android. The annotation. Nullable Bundle savedInstanceState) {/ / collect registration List, that is, mActivityLifecycleCallbacks will be (List), Converted to an array Object [] callbacks = collectActivityLifecycleCallbacks (); if (callbacks ! = null) { for (int i=0; i<callbacks.length; I++) {/ / call the corresponding callback method ((ActivityLifecycleCallbacks) callbacks [I]). The onActivityCreated (activity, savedInstanceState); }}}Copy the code
While the above is just an analysis of onCreate, the other methods follow the same path.
Each time an Activity is in a different phase, it checks whether the Application is listening for its lifecycle, and if so, it tells the listener what phase it is in. 2. If you override the Activity’s corresponding method and add printing, the Application callback will be executed before printing in the Activity because it is executed in the Activity’s parent class.
Above is the carding of the Activity lifecycle, the next will analyze onSaveInstanceState/onRestoreInstanceState principle and application scenarios, and introducing the Jetpack ViewModel in contrast.
Transparent Activity/ lifecycle listening Demo Please see: Github collection
This article is based on Android 10.0
If you like, please like, pay attention to your encouragement is my motivation to move forward
Continue to update, with me step by step system, in-depth study of Android
4, View Measure/Layout/Draw 5, Android events distribution of full service 6, Android invalidate postInvalidate/requestLayout thoroughly clarify 7, how do you determine the Android Window size/onMeasure () to be executed multiple times Android event driver Handler-message-Looper 9, Android keyboard in one move 10, Android coordinates completely clear 11, Android Activity/Window/View background Android IPC series 14, Android Storage series 15, Java concurrent series no longer confusion 16, Java thread pool series 17, Android Jetpack Practice and Principle series