An analysis of the activity life cycle of Android (II.)

Source: Internet
Author: User

?? In the previous article, we mainly analyzed the life cycle of activity and its methods, this article mainly deals with the life cycle under the abnormal circumstance of activity.

Activity Abnormal life cycle

?? The abnormal life cycle refers to the activity being reclaimed by the system or the configuration of the current device is changed (generally referred to as the screen switch), which causes the activity to be destroyed and rebuilt. The life cycle of the anomaly is divided into the following two scenarios:

    • 1, the related system configuration changes cause activity to be killed and re-created (generally refers to the screen switch)
    • 2. Low-priority activity is killed due to insufficient memory

      1, the related system configuration changes cause activity to be killed and re-created (generally refers to the screen switch)

      We first analyze the first situation, when the activity is in a vertical state, if the screen is suddenly rotated, due to changes in the system configuration, the activity will be destroyed and recreated by default, of course, we can prevent this situation by human intervention. Here we first use the test code of the previous article to verify this process, with the following code:

 PackageCom.cmcm.activitylifecycle;ImportAndroid.content.Intent;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button; Public  class mainactivity extends appcompatactivity {Button BT;/** * is called when activity is created * @param savedinstancestate */    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); LOGUTILS.E ("OnCreate is Invoke!!!");        bt= (Button) Findviewbyid (R.ID.BT); Bt.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Intent i =NewIntent (mainactivity. This, Secondactivity.class);            StartActivity (i);    }        }); }@Override    protected void onsaveinstancestate(Bundle outstate) {Super. Onsaveinstancestate (Outstate); LOGUTILS.E ("Onsaveinstancestate is Invoke!!!"); }@Override    protected void onrestoreinstancestate(Bundle savedinstancestate) {Super. Onrestoreinstancestate (Savedinstancestate); LOGUTILS.E ("Onrestoreinstancestate is Invoke!!!"); }/** * is called when activity is returned from the background back to the foreground * /    @Override    protected void Onrestart() {Super. Onrestart (); LOGUTILS.E ("Onrestart is Invoke!!!"); }/** *activity created or returned from the background back to the foreground is called */    @Override    protected void OnStart() {Super. OnStart (); LOGUTILS.E ("OnStart is Invoke!!!"); }/** *activity is created or called from the background and back to the foreground * /    @Override    protected void Onresume() {Super. Onresume (); LOGUTILS.E ("Onresume is Invoke!!!"); }/** * Activity is overwritten to the bottom or the lock screen is called */    @Override    protected void OnPause() {Super. OnPause (); LOGUTILS.E ("OnPause is Invoke!!!"); }/** * Called when exiting active activity or jumping to new activity    @Override    protected void OnStop() {Super. OnStop (); LOGUTILS.E ("OnStop is Invoke!!!"); }/** * is called when exiting the current activity, the activity ends after the call.    @Override    protected void OnDestroy() {Super. OnDestroy (); LOGUTILS.E ("OnDestroy is Invoke!!!"); }}

?? The code is simple, we rewrite the Onsaveinstancestate method and the Onrestoreinstancestate method, which we'll cover in detail later, here we'll look at the results of the operation:

?? We can see from the log that when we start the activity normally, the Oncreate,onstart,onresume method will be called back in turn, and if we are to adjust the vertical screen activity to a horizontal screen, we can find OnPause, The onsaveinstancestate,onstop,ondestroy,oncreate,onstart,onrestoreinstancestate,onresume is called in turn, and we can tell from the method we call. The activity is first destroyed and recreated, with the following abnormal life cycle:

?? Now we probably all know the flow of the abnormal life cycle, but what do onsaveinstancestate and Onrestoreinstancestate methods do? In fact, these two methods are automatically called by the system, when the system configuration changes, the activity will be destroyed, that is, Onpause,onstop,ondestroy will be called sequentially, and because the activity is destroyed in exceptional circumstances, The Android system automatically calls the Onsaveinstancestate method to save state information for the current activity. So we can store some data in the Onsaveinstancestate method so that it can be recovered after the activity is rebuilt, of course, the method must be called before the OnStop method, that is, before the activity stops. The timing of the call to the OnPause method can be arbitrary. With the log information above, we can also know that when the activity is recreated, the system will call the Onrestoreinstancestate method, The bundle objects saved by the Onsaveinstancestate method are passed to the Onrestoreinstancestate and OnCreate methods as parameters while the activity is destroyed. So we can use the Onrestoreinstancestate and OnCreate methods to determine if the activity is recreated, and if it is rebuilt, we can restore the previous data. From the log information, we can see that the Onrestoreinstancestate method call time is after onstart.It is important to note here that Onsaveinstancestate and onrestoreinstancestate are only called when the activity terminates abnormally, and the two methods are not called normally.
?? Here you may have a question, onrestoreinstancestate and OnCreate methods can be used for data recovery, which is the use of which ah? In fact, both can, the difference is that Once the Onrestoreinstancestate method is callback by the system, its parameter bundle must not be empty, no additional judgment is required, and the bundle of oncreate does not necessarily have a value, because if the activity is started normally, The bundle parameter does not have a value, so we need additional judgment conditions, although both can recover data, but prefer the Onrestoreinstancestate method.
?? And finally, what we need to know is that in the Onsaveinstancestate method and the Onrestoreinstancestate method, the Android system will automatically help us recover certain data, such as the view structure of the current activity, the data of the text box, The scroll position of the ListView and so on, these view related state systems will help us recover, because each view also has the Onsaveinstancestate method and the Onrestoreinstancestate method, we test an example, Enter the data in the EditText text box and switch to the screen, the result is as follows:

As you can see, the system does help us restore the activity structure and view data.

2. Low-priority activity is killed due to insufficient memory

?? Let's talk about it. Insufficient memory causes low-priority activity to be killed, and then rebuilt, without even having to talk about the stored procedure and recovery process of the data is basically not worse than the above situation. Let's keep talking about the activity being killed, and when the system is out of memory, the system will kill the target acitivity process to reclaim the memory by a certain priority. The activity's Onsaveinstancestate method is then called to store the data, and the Onrestoreinstancestate method is invoked to recover the data as the subsequent activity resumes. So we should try to keep it as high as possible so as not to be killed in the process of activity. What is the higher priority? To get a better understanding of the problem, let's start with a new topic, Android process level.

Android Process Hierarchy

?? The most important process in the Android system is called the foreground process, followed by any visible processes, service processes, background processes, and finally empty processes. Next we will proceed further.
?? Before we start, we need to make a clear point, when we talk about process priorities in terms of components such as activity, service, but note that these priorities are at the level of the process, not at the component level. As long as one component is a foreground process, the entire process becomes the foreground process. At the same time we need to know that most applications are single-process, and if we have different parts or parts of the life cycle that vary greatly, we strongly recommend dividing them into different processes so that the heavyweight process can be recycled as early as possible.
With that in mind, let's take a look at the following picture (figure from who lives and who dies?). Process priorities on Android):

We can see a total of 5 priority threads, Foreground Processes, Visible Processes, Service Processes, Background Processes, Empty Processes;

    • 1.Foreground Processes (foreground process)

?? The number of foreground processes in the system is very small (as can be seen), and the foreground process is almost never killed. Killing a foreground process is only selected if the memory is low to ensure that all foreground processes are running concurrently. The following are the foreground processes:
A. Activity that is interacting with the user at the foreground
B. Service bound to the foreground activity
C. Service that called the Startforeground () method
D. Service that is executing the oncreate (), OnStart (), or OnDestroy () method
E. The broadcastreceiver of the OnReceive () method is being executed.
Any process that contains any of these cases is a foreground process. Of course, some of the activity is dependent on their colleagues to become the foreground process, may also rely on bound service. Any process, if it holds a service bound to the foreground activity, it is also given the same foreground priority.

    • 2.Visible Processes (visual process)

?? At this point, if an activity is visible but not in the foreground, as if a dialog box is popped in the activity, causing the activity to be visible but not interacting with the user in the background, the process can be considered a visible process, and we must also understand that the activity's Bound service and content provider are also in a visible process state. This is also to ensure that the processes on which the activity is used are not prematurely killed. However, it is important to note that just being visible does not mean that you cannot be killed. If the memory pressure from the foreground process is too high, the visible process may still be killed. From the user's perspective, this means that the visible activity behind the current activity is replaced by a black screen. Of course, if we rebuild the activity correctly, our process and activity will recover immediately without loss of data after the foreground activity is closed.

    • 3.Service Processes (Service process)

?? If we start a service service through StartService (), it is considered a process. This is the case for many apps that do processing in the background, such as asynchronously loading data, acquiring time-consuming resources, and so on, without immediately becoming a front-end service. This is the most common and reasonable background processing, which can only be killed if the visible process and the foreground process are running out of memory.

    • 4.Background Processes (Background process)

?? If our activity is currently the foreground process, but this time, we point the home key, will cause the Onpause,onstop method to be called, our process has become the background process, of course, our background process will not be killed immediately, so these processes will remain for a period of time, It is not recycled until the higher priority processes require memory, and is in the least recently used order (the least used will be prioritized for recycling). Most of the time we find that the memory of the phone is mostly occupied by the background app process, and the advantage of Android is that we can have a better user experience by not having to reassign and load resources the next time we reopen the app for this process.
。 However, when the memory is low, they will still be killed, so we should be as visible as the activity processing, should be able to rebuild the activity without losing the user state, in order to achieve a better user experience.

    • 5.Empty Processes (Empty process)

?? At any level, empty processes are the lowest priority. If our process does not belong to the above category, then it is an empty process. Empty processes are not active components, but are reserved for caching purposes (in order to use memory more efficiently instead of being completely freed), as long as the Android system memory needs to be able to kill them at any time.

Well, now we should have a clear idea of the Android process, back to the previous activity memory is not enough to be killed by the Android system topic, in order to prevent some important activity is not accidentally killed, We should keep the activity of the current process in a high priority, such as making it a foreground process, or binding through a service, or making it a separate process. Of course, if it is really unfortunate to be killed, we should try to save and recover the data through the Onsaveinstancestate method and the Onrestoreinstancestate method in order to get a better user experience.

Solve the problem of destruction and reconstruction of activity

Through the above analysis we know that when the system configuration changes, the activity will be rebuilt, there is no way to make it not rebuilt it? The method is natural, that is, we can assign the Configchange property to activity, and when we do not want activity to destroy the rebuild after the screen is rotated, we can set configchange= "orientation"; When the SDK version is greater than 13 o'clock , we also need to add an extra value for "screensize", meaning the following for both values:
Orientation: Screen orientation Changes, configure this parameter can solve the vertical and horizontal screen switching, activity reconstruction problem (API<13)
ScreenSize: When the device is rotated, the screen size changes, the parameter must be configured after api>13 to ensure that the switch does not cause activity reconstruction.
In plain terms, when the two parameters are set, the activity will not be rebuilt and the previous related methods will not be called when the screen is switched, instead of the callback onconfigurationchanged method. The case code is as follows:

<?xml version= "1.0" encoding= "Utf-8"?><manifest xmlns:android="Http://schemas.android.com/apk/res/android"  package ="Com.cmcm.activitylifecycle" >        <applicationandroid:allowbackup="true"android:icon="@mipmap/ Ic_launcher "android:label=" @string/app_name "android:supportsrtl=" True "android:theme=" @style/apptheme " >                                                <activity android:name=". Mainactivity "android:configchanges=" Orientation|screensize " >                        <intent-filter>                <action android:name="Android.intent.action.MAIN" />                <category android:name="Android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name=". Secondactivity "></activity>    </Application></manifest>

In the mainactivity we rewrite the onconfigurationchanged, the prototype is as follows:

    @Override    publicvoidonConfigurationChanged(Configuration newConfig) {        super.onConfigurationChanged(newConfig);        LogUtils.e("onConfigurationChanged is invoke!!!");    }

We run the program, and then we perform a screen shift to see the printed log information:

From log you can see that the activity does not rebuild, and there is no callback Onsaveintancestate method and Restoreinstancestate method to store or restore the data. Instead, the Onconfigurationchanged method is called back, so we can do some extra work in this way in this case. OK, this is the right place to talk.

An analysis of the activity life cycle of Android (I.)



Main references:
Explore the art of Android development
Http://www.androidchina.net/4391.html

An analysis of the activity life cycle of Android (II.)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.