[Android] Life cycle of activity

Source: Internet
Author: User

To learn more about Android, you have to understand the life cycle of an Android software, understand the process of creating, starting, stopping, pausing, restarting, and destroying an activity, knowing what functions are called at each stage to handle different situations, and here we say the life cycle of the activity.

1. Activity stack

The activity in Android is cascading, and each new activity we launch will be overwritten with the original activity, and then clicking the back key destroys the top activity, and the following activity will be displayed again.

In fact, Android is the use of tasks to manage activities, a task is a set of activities stored in the stack, this stack is also known as the activity stack. The stack is a last-in-first-out data structure that, by default, is placed in the stack on the back stack and at the top of the stack whenever we start a new activity. And every time we press the back key or call the finish () method to destroy an activity, the activity at the top of the stack will be out of the stack, and the previous stack activity will be back at the top of the stack. The system always displays the activity at the top of the stack to the user.

2. Status of the activity

Each activity may have a maximum of four states in its life cycle.

    1. Running state
      When an activity is at the top of the stack on the active stack, the activity is in the running state. The last thing the system wants to recycle is a running activity, because it brings a very poor user experience.

    2. Paused state
      When an activity is no longer in the top position of the stack, but is still visible, the activity enters a paused state. You may think that since the activity is not at the top of the stack, how can it be visible? This is because not every activity will fill the entire screen, such as dialog box activity will only occupy part of the screen in the middle of the area, you will soon see this activity. The suspended activity is still completely alive, and the system is unwilling to recycle it (as it is visible, the recycling of what is seen will have a bad impact on the user experience), and the system will consider recycling this activity only when the memory is very low.

    3. Stop State
      When an activity is no longer at the top of the stack and is completely invisible, it enters a stop state. The system will still save the appropriate state and member variables for this activity, but this is not completely reliable, and when memory is needed elsewhere, the activity in the stopped state may be reclaimed by the system.

    4. Destroy state
      When an activity is removed from the activity stack, it becomes a destroy state. The system will most likely recycle activities in this State, thus ensuring that the phone has sufficient memory.

3. Lifetime of activity

The

Activity class defines seven callback methods, covering every aspect of the activity life cycle, and let me introduce each of the seven methods below.
1. OnCreate ()
This method you have seen many times, we have rewritten this method in each activity, it will be called when the activity is created for the first time. You should perform initialization of activities in this method, such as loading layouts, binding events, and so on.
2. OnStart ()
This method is called when the activity becomes visible from invisible.
3. Onresume ()
This method is called when the activity is ready to interact with the user. At this point the activity must be at the top of the stack, and it is in a running state.
4. OnPause ()
This method is called when the system is ready to start or resume another activity. We usually release some CPU-consuming resources in this method and save some key data, but this method must be executed quickly, otherwise it will affect the use of the new stack top activity.
5. OnStop ()
This method is called when the activity is completely invisible. The main difference between it and the OnPause () method is that if the new activity started is a dialog-box activity, then the OnPause () method will be executed, and the OnStop () method will not execute.
6. OnDestroy ()
This method is called before the activity is destroyed and then the state of the activity becomes destroyed.
7. Onrestart ()
This method is called before the activity is changed from a stopped state to a running state, that is, the activity is restarted.

In addition to the Onrestart () method in the above seven methods, the others are 22 relative, and the activity can be divided into three lifetimes.
1. Full lifetime
The activity between the OnCreate () method and the OnDestroy () method is the complete survival period. In general, an activity completes various initialization operations in the OnCreate () method, while freeing the memory in the OnDestroy () method.
2. Visible lifetime
The activity that is experienced between the OnStart () method and the OnStop () method is the visible lifetime. During the visible lifetime, activities are always visible to the user, even though they may not be able to interact with the user. Through these two methods, we can reasonably manage the resources that are visible to the user. For example, the resource is loaded in the OnStart () method, and the resource is freed in the OnStop () method to ensure that the inactive activity does not consume too much memory.
3. Foreground lifetime
The activity between the Onresume () method and the OnPause () method is the foreground lifetime. In the foreground life period, the activity is always in the running state, at this time the activity is can and the user to each other, we usually see and contact the most also this state of activity.

4. Active life-time instances

With so much theoretical knowledge, it's time to do the actual combat, and below we will use an example that allows you to experience the life cycle of the activity more intuitively.

This time we are not prepared to modify the project based on Activitytest, but to create a new project. Therefore, first close the Activitytest project, and then create a new Activitylifecycletest project. The process of creating a new project you should have been very clear, do not need me to repeat, this time we allow ADT to help us create an activity automatically, this can save a lot of work, create the activity name and layout names using the default values. So the main activity is created, and we need to create two more sub-activities, Normalactivity and dialogactivity, which are implemented in the following step.

Create a new Normal_layout.xml file with the code as follows:

<linearlayout xmlns:android="Http://schemas.android.com/apk/res/android"  Android:layout_width="Match_parent"android:layout_height="Match_parent"  Android:orientation="vertical" >                <TextViewandroid:layout_width="Match_parent"android:layout_ Height="Wrap_content"android:text="This is a normal activity" />            </linearlayout>

In this layout we are very simple to use a TextView, and then the same way, we create a new Dialog_layout.xml file, the code is as follows:

<linearlayout xmlns:android="Http://schemas.android.com/apk/res/android"  Android:layout_width="Match_parent"android:layout_height="Match_parent"  Android:orientation="vertical" >                <TextViewandroid:layout_width="Match_parent"android:layout_height= "Wrap_content" Android:text="This is a dialog activity" />            </linearlayout>

The code for the two layout files is almost indistinguishable, just the text displayed is different. Then the new normalactivity inherits from the Activity, and the code looks like this:

publicclass NormalActivity extends Activity {    @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        requestWindowFeature(Window.FEATURE_NO_TITLE);        setContentView(R.layout.normal_layout);    }}

We loaded the normal_layout layout in the normalactivity. The same method, and then the new dialogactivity inherits from the Activity, the code looks like this:

publicclass DialogActivity extends Activity {    @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        requestWindowFeature(Window.FEATURE_NO_TITLE);        setContentView(R.layout.dialog_layout);    }}

We loaded the dialog_layout layout in the dialogactivity. In fact, from the name you can see that the two activities are ordinary activities, one is a dialog-type activities. But now, anyway, the code for both activities is almost identical, where does it show that the activity is set up as a dialog box? Don't worry, we'll start setting up right now. Add the following code to the Androidmanifest.xml tag:

<activity android:name=".NormalActivity" ></activity><activity android:name=".DialogActivity" android:theme="@android:style/Theme.Dialog" ></activity>

There are two activities to register, but Dialogactivity's registration code is somewhat different, it uses a Android:theme attribute, which is used to assign the theme to the current activity, the Android system has many themes to choose from, Of course we can also customize our own theme, and here @android:style/theme.dialog is no doubt to let dialogactivity use dialog-box theme. Next we modify the Activity_main.xml and re-customize the layout of our main activity:

<linearlayout xmlns:android="Http://schemas.android.com/apk/res/android"Android:layout_width="Match_parent"android:layout_height="Match_parent"<button android:ID="@+id/start_normal_activity"Android:layout_width="Match_parent"android:layout_height="Wrap_content"Android:text="Start normalactivity"/> <button android:ID="@+id/start_dialog_activity"Android:layout_width="Match_parent"android:layout_height="Wrap_content"Android:text="Start dialogactivity"/></linearlayout>

The auto-generated layout code is a bit complicated, and we're completely replacing it, still using the most familiar linearlayout, and then adding two buttons, one for starting normalactivity and one for starting dialogactivity.

Finally, modify the code in Mainactivity as follows:

 Public  class mainactivity extends Activity {     Public Static FinalString TAG ="Mainactivity";@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); LOG.D (TAG,"OnCreate");        Requestwindowfeature (Window.feature_no_title);        Setcontentview (R.layout.activity_main);        Button startnormalactivity = (button) Findviewbyid (r.id.start_normal_activity);        Button startdialogactivity = (button) Findviewbyid (r.id.start_dialog_activity); Startnormalactivity.setonclicklistener (NewOnclicklistener () {@Override         Public void OnClick(View v) {Intent Intent =NewIntent (mainactivity. This, Normalactivity.class);        StartActivity (Intent);        }        }); Startdialogactivity.setonclicklistener (NewOnclicklistener () {@Override         Public void OnClick(View v) {Intent Intent =NewIntent (mainactivity. This, Dialogactivity.class);        StartActivity (Intent);    }        }); }@Override    protected void OnStart() {Super. OnStart (); LOG.D (TAG,"OnStart"); }@Override    protected void Onresume() {Super. Onresume (); LOG.D (TAG,"Onresume"); }@Override    protected void OnPause() {Super. OnPause (); LOG.D (TAG,"OnPause"); }@Override    protected void OnStop() {Super. OnStop (); LOG.D (TAG,"OnStop"); }@Override    protected void OnDestroy() {Super. OnDestroy (); LOG.D (TAG,"OnDestroy"); }@Override    protected void Onrestart() {Super. Onrestart (); LOG.D (TAG,"Onrestart"); }}

In the OnCreate () method, we register the click event for two buttons respectively, click the first button will start Normalactivity, click the second button will start dialogactivity. A sentence is then printed separately in the activity's seven callback methods, so that the life cycle of the activity can be more intuitively understood by observing the log.

Now run the program, Effect:

5. What if the activity is destroyed?

As we have said earlier, when an activity enters a stopped state, it is possible that the system will be recycled. So imagine the following scenario, the application has an activity a, the user on the basis of activity A to start the activity B, the activity A has entered the stop state, this time because the system memory is not enough, the activity A is recycled, and then the user press the back key to return to activity A, what happens? In fact, it will normally show activity a, except that it does not execute the Onrestart () method, but instead executes the onCreate () method of activity A, because activity a is recreated in this case. This looks like everything is fine, but don't overlook an important issue where temporary data and status may be present in activity A. For example, there is a text input box in the mainactivity, now you enter a paragraph of text, and then start normalactivity, then mainactivity because the system memory is not enough to be recycled, after a while you click the back key to return to Mainactivity, you'll find that the text you just typed is all gone, because Mainactivity was re-created.

If this happens in our application, it can seriously affect the user experience, so we have to find a way to solve the problem. As you can see in the documentation, there is also a onsaveinstancestate () callback method in the activity that guarantees that it must be called before the activity is recycled, so we can use this method to solve the problem that the temporary data is not saved when the activity is recycled. The Onsaveinstancestate () method carries a bundle type parameter, and the bundle provides a series of methods for saving the data, such as using the Putstring () method to hold the string, saving the integer data using the Putint () method, and so on. Each save method needs to pass in two parameters, the first parameter is the key, which is used to take the value from the Bundle later, and the second parameter is the actual content to be saved.

You can save the temporary data by adding the following code to the mainactivity:

@OverrideprotectedvoidonSaveInstanceState(Bundle outState) {    super.onSaveInstanceState(outState);    "Something you just typed";    outState.putString("data_key", tempData);}

The data has been saved, so where should we restore it? Careful you may have long ago found that the OnCreate () method we have been using actually has a parameter of Bundle type. This parameter is null in general, but when the activity is saved by the Onsaveinstancestate () method before it is reclaimed by the system, this parameter takes all the data that was previously saved, and we only need to retrieve the data by the corresponding value method.

Modify the Mainactivity OnCreate () method as follows:

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    "onCreate");    requestWindowFeature(Window.FEATURE_NO_TITLE);    setContentView(R.layout.activity_main);    ifnull) {        String tempData = savedInstanceState.getString("data_key");        Log.d(TAG, tempData);    }    ……}

Take out the value and then do the corresponding recovery operation, for example, the text content is re-assigned to the text input box, here we simply print.

Do you realize that using bundles to save and extract data is a bit familiar? That's right! A similar approach is used when we use Intent to pass data. Here to remind you that Intent can also be used in conjunction with the bundle to pass the data, first of all the data needed to be passed to the bundle object, and then the bundle object stored in the Intent. After the target activity, the bundle is removed from the Intent and the data is extracted from the bundle one by one.

[Android] Life cycle of activity

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.