Ziyue: Zhixin, Zhixin. Forum
The same is true for learning technology. For technical documents or classic technical books, it is almost impossible to read them all over again. Therefore, we need to read them several times in detail, to comprehend the essence of the author's thoughts.
Recently, I think about the lifecycle of an activity. NLP has read related books and official documents, and has made great achievements. It has greatly improved its cognition, I would like to share with you here.
Friends familiar with javaee know Servlet technology. To implement a servlet, We need to inherit the corresponding base class and rewrite its method, these methods will be called by the servlet container at the appropriate time. In fact, the activity execution mechanism in Android is similar to servlet. Android is equivalent to servlet container, and activity is equivalent to servlet. Our activity is in this container, all processes such as instance creation, initialization, and instance Destruction are called by containers. This is also called "don't call me, I'll call you. "mechanism.
Let's take a look at this classic Life Cycle flowchart:
I believe many of my friends have read this flowchart and have basically understood the several processes of the activity lifecycle. Let's talk about these processes.
1. Start activity: the system first calls the oncreate method, then calls the onstart method, and finally calls onresume. The activity enters the execution status.
2. The current activity is overwritten by another activity or locked: the system will call the onpause method to pause the operation of the current activity.
3. The current activity is overwritten to the front-end or unlock screen: The system calls the onresume method and enters the execution status again.
4. Switch the current activity to the new activity interface or press the Home Key to return to the main screen and return to the background: the system will first call the onpause method and then call the onstop method to enter the stuck state.
5. the user returns to this activity: the system will first call the onrestart method, then call the onstart method, and finally call the onresume method to enter the execution status again.
6. the current activity is in the overwriting status or the background is invisible, that is, steps 1 and 2. If the system memory is insufficient, the current activity is killed and the user returns to the current activity: call the oncreate method, onstart method, and onresume method again to enter the execution status.
7. Exit the current activity: the system first calls the onpause method, then calls the onstop method, and finally calls the ondestory method to end the current activity.
However, knowing this is not enough. We must experiment with it to gain a deep understanding.
The following uses examples to illustrate the specific process of the lifecycle. Create a project named lifecycle and create an activity named lifecycleactivity, for example:
Package COM. scott. lifecycle; import android. app. activity; import android. content. context; import android. content. intent; import android. OS. bundle; import android. util. log; import android. view. view; import android. widget. button; public class lifecycleactivity extends activity {Private Static final string tag = "lifecycleactivity"; private context = This; private int Param = 1; // called @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); log. I (TAG, "oncreate called. "); setcontentview (R. layout. lifecycle); button BTN = (button) findviewbyid (R. id. BTN); BTN. setonclicklistener (new view. onclicklistener () {@ overridepublic void onclick (view v) {intent = new intent (context, targetactivity. class); startactivity (intent) ;}}) ;}// call @ override protected void onstart () {super. onstart (); log. I (TAG, "onstart called. ");} // The activity is called @ override protected void onrestart () {super. onrestart (); log. I (TAG, "onrestart called. ");} // The activity is called @ override protected void onresume () {super. onresume (); log. I (TAG, "onresume called. ");} // called when the activity form gets or loses focus, after onresume or after onpause/* @ override public void onwindowfocuschanged (Boolean hasfocus) {super. onwindowfocuschanged (hasfocus); log. I (TAG, "onwindowfocuschanged called. ");} * // The activity is overwritten below or called @ override protected void onpause () {super. onpause (); log. I (TAG, "onpause called. "); // after running onpause or onstop, the activity may be killed due to insufficient system resources, therefore, it is necessary to save persistent data here} // exit the current activity or be called @ override protected void onstop () {super. onstop (); log. I (TAG, "onstop called. ");} // called when exiting the current activity. After the call, the activity ends @ override protected void ondestroy () {super. ondestroy (); log. I (TAG, "ondestory called. ");}/*** called when the activity is killed by the system. * For example, when the screen direction changes, the activity is destroyed and re-built. The current activity is in the background, and the system resource is insufficient to kill it. * In addition, this method is also called when you jump to another activity or press the Home Key to return to the home screen. The system wants to save the status of the current view component. * called before onpause. * // @ overrideprotected void onsaveinstancestate (bundle outstate) {outstate. putint ("Param", Param); log. I (TAG, "onsaveinstancestate called. put Param: "+ PARAM); super. onsaveinstancestate (outstate);}/*** called when the activity is killed by the system and rebuilt. * For example, when the screen direction changes, the activity is destroyed and re-built. The current activity is in the background, the system resource is insufficient to kill it, and the user starts the activity again. * in both cases, onrestoreinstancestate is called after onstart. * // @ overrideprotected void onrestoreinstancestate (bundle savedinstancestate) {Param = savedinstancestate. getint ("Param"); log. I (TAG, "onrestoreinstancestate called. get Param: "+ PARAM); super. onrestoreinstancestate (savedinstancestate );}}
In addition to several common methods, we have added the onwindowfocuschanged, onsaveinstancestate, and onrestoreinstancestate methods:
1. onwindowfocuschanged method: This method is called when the activity form gets or loses focus. For example, it is displayed in front of the current user for the first time when it is created; the current activity is overwritten by other activities; the current activity is switched to another activity or the home key is pressed to return to the main screen, and the user exits the current activity. In the preceding cases, onwindowfocuschanged is called. When an activity is created, it is called after onresume. When the activity is overwritten or left in the background or exited, it is called after onpause, as shown in the following figure:
This method is very practical in some cases. For example, when a program is started, it may not be possible to obtain the size of a specific view component in oncreate, since the window object of the form has not been created yet, we need to obtain it in onwindowfocuschanged at this time. If you have read the Frame Animation article of Android animation I wrote, you will know, at that time, I tried to load the Frame Animation in oncreate because the window object of the form was not initialized, so I finally put the code for loading the animation into onwindowfocuschanged, which solved the problem. But you may wonder why I stare at it in the Code. Because every operation of the current activity has its running log, I am worried that this will affect the definition of the entire process, so you just need to know the order of the application's combination and running.
2. onsaveinstancestate: (1) after the activity is overwritten or deprecated to the background, the system will kill the activity due to insufficient resources. (2) This method will be called when the user changes the screen direction; (3) This method is called when the current activity jumps to another activity or presses the Home Key to return to the home screen. In the first case, we cannot guarantee when the system will be scheduled based on resource shortage. In the other case, when the screen is flipped, the system first destroys the current activity, then recreate a new one. When this method is called, we can save some temporary data. In the third case, the system calls this method to save the status of each view component of the current form. The call sequence of onsaveinstancestate is prior to onpause.
3. onrestoreinstancestate: (1) after the activity is overwritten or deprecated to the background, the system will kill the activity due to insufficient resources, and the user will return to the activity. (2) this method is called during the reconstruction process when the user changes the screen direction. We can rewrite this method to restore some temporary data. Onrestoreinstancestate is called after onstart.
After the above three relatively unfamiliar methods are introduced, let's take a look at this activity to see what the lifecycle is like:
1. Start activity:
After the system calls oncreate and onstart, onresume is called. Since then, the activity enters the execution status.
2. Jump to another activity, or press the Home Key to return to the home screen:
We can see that the onsaveinstancestate method is called before onpause, and note that onstop is called after onpause in the background.
3. Return to the front-end from the background:
The system first calls the onrestart method, then calls the onstart method, and finally calls the onresume method. The activity enters the execution status again.
4. modify targetactivity in androidmanifest. in XML, set the Android: Theme attribute to @ Android: style/theme. dialog, and then click the button in lifecycleactivity. The jump behavior is changed to overwriting lifecycleactivity by targetactivity. The method called at this time is:
Note that when we click the button, we only press the lock screen key, and the running effect is also as shown above.
We noticed that the onpause method of lifecycleactivity is called and the onstop method is not called. Because the lifecycleactivity does not return to the background, it is only overwritten or locked; The onsaveinstancestate is called before onpause.
5. Press the rollback key to make lifecycleactivity back to the front, or press the unlock key to unlock the screen:
At this time, only the onresume method is called and the execution status is directly re-displayed.
6. Exit:
The ondestory method is called at last, marking the end of lifecycleactivity.
It seems that there is no onrestoreinstancestate in the whole process. This is not surprising because we have mentioned it before, onrestoreinstancestate is called only when the user returns to the activity after killing the activity that is not in the foreground, or when the user changes the screen direction. We want to demonstrate that the first case is more difficult than the second case. We can use the other case to demonstrate the detailed process. By the way, I also want to explain how the screen orientation changes.
First, we will introduce the screen orientation of the activity.
We can specify a specific direction for an activity. Even if we turn the screen direction, the display direction will not change:
1. Portrait screen: Set Android: screenorientation = "portrait" for the specified activity in androidmanifest. XML, or specify the following in the oncreate method:
Setrequestedorientation (activityinfo. screen_orientation_portrait); // portrait Screen
2. horizontal screen: In androidmanifest. XML, set Android: screenorientation = "Landscape" for the specified activity, or in the oncreate method:
Setrequestedorientation (activityinfo. screen_orientation_landscape); // landscape Screen
Setting a specific direction for the activity in the application is a frequently used method, which can save us a lot of unnecessary trouble. However, today we are talking about the lifecycle when the screen direction changes, so we are not trying to fix the screen direction.
The following describes the life cycle of screen conversion in combination with an instance. We create an activity named orientationactivity, for example:
Package COM. scott. lifecycle; import android. app. activity; import android. content. res. configuration; import android. OS. bundle; import android. util. log; public class orientationactivity extends activity {Private Static final string tag = "orientationactivity"; private int Param = 1; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. orientation_portrait); log. I (TAG, "oncreate called. ") ;}@ overrideprotected void onstart () {super. onstart (); log. I (TAG, "onstart called. ") ;}@ overrideprotected void onrestart () {super. onrestart (); log. I (TAG, "onrestart called. ") ;}@ overrideprotected void onresume () {super. onresume (); log. I (TAG, "onresume called. ") ;}@ overrideprotected void onpause () {super. onpause (); log. I (TAG, "onpause called. ") ;}@ overrideprotected void onstop () {super. onstop (); log. I (TAG, "onstop called. ") ;}@ overrideprotected void ondestroy () {super. ondestroy (); log. I (TAG, "ondestory called. ") ;}@ overrideprotected void onsaveinstancestate (bundle outstate) {outstate. putint ("Param", Param); log. I (TAG, "onsaveinstancestate called. put Param: "+ PARAM); super. onsaveinstancestate (outstate) ;}@ overrideprotected void onrestoreinstancestate (bundle savedinstancestate) {Param = savedinstancestate. getint ("Param"); log. I (TAG, "onrestoreinstancestate called. get Param: "+ PARAM); super. onrestoreinstancestate (savedinstancestate);} // when the direction of Android: configchanges = "orientation" is changed, onconfigurationchanged is called @ overridepublic void onconfigurationchanged (configuration newconfig) {super. onconfigurationchanged (newconfig); log. I (TAG, "onconfigurationchanged called. "); Switch (newconfig. orientation) {Case configuration. orientation_portrait: setcontentview (R. layout. orientation_portrait); break; Case configuration. orientation_landscape: setcontentview (R. layout. orientation_landscape); break ;}}}
First, we need to go to "Settings-> display" and select "auto-rotate screen" to indicate that we can automatically rotate the screen in the direction, and then we can continue the trial process, when we rotate the screen, we find that the system first destroys the current activity and then creates a new one:
The system first calls the onsaveinstancestate method, and saves a temporary token to the bundle object. Then, after the activity is rebuilt, we successfully retrieve the token number.
To avoid such destruction and reconstruction, we need. in XML, configure Android: configchanges = "orientation" for the corresponding orientationactivity <activity>, and then try again. I tried to perform four rotations and print the following:
It can be seen that only the onconfigurationchanged method is called at each rotation direction, and the reconstruction process is not destroyed.
The following are some notes:
1. If <activity> is configured with the Android: screenorientation attribute, the Android: configchanges = "orientation" will become invalid.
2. the simulator differs greatly from the real machine. In the simulator, assume that the Android: configchanges attribute is not configured or the configuration value is orientation. You can run the destroy command on the horizontal screen-> recreate the task and run the command twice on the portrait screen. Real machines are all once. Assume that Android: configchanges = "orientation | keyboardhidden" is configured in the simulator (for example, android4.0, orientation | keyboardhidden | screensize "), and onconfigurationchanged is run on the portrait screen, split the landscape screen twice. Real machines are all once.
The lifecycle of an activity is closely related to the robustness of the program. I hope that you will be able to understand and use the activity well.
One of the basic summaries is activity lifecycle.