The life cycle of Android four components

Source: Internet
Author: User

Before introducing the life cycle, let's start with the concept of a task

The task is actually a stack of activity. It is composed of one or more activity to complete a complete user experience, in other words, the task is "application" (can be one or more, for example, suppose you want to let users see a street map of a place.) There is already an activity with this function, and the work you need to do is put the request information into a intent object and pass it to StartActivity (). The map browser will then show the map. And when the user presses the Back button, your activity will again appear on the screen, when the task is composed of 2 applications of related activity is the bottom of the activity to start the entire task, the top of the stack is the current user can interact with the activity , when one activity launches another, the new activity is pushed into the stack and becomes the activity currently running. The previous activity remains in the stack. When the user presses the back key, the current activity is out of the stack, and the previous one reverts to the currently running activity. The stack is actually an object, the activity in the stack will never reflow, will only press in or eject, so if a situation such as the need for more than one map browser, it will cause a task to appear multiple instances of the same activity subclass exist simultaneously.

All activity in the task is moved as a whole. The entire task (that is, the activity stack) can be moved to the foreground or back to the background. For example, for example, the current task has four activity── in the stack, three under the current activity. When the user presses the home key, it goes back to the application loader and selects a new application (that is, a new task). The current task is in the background and the root activity of the new task is displayed. Then, after a little while, the user returns to the application loader again and selects the previous application (the previous task). So the task, with all the four activity in the stack, once again to the front desk. When the user presses the back key, the screen does not show the activity that the user has just left (the root of the previous task

Activity). Instead, the topmost activity in the current task's stack pops up, and the last activity in the same task is displayed.

Activity stack: Advanced post-out rules

The Android system is a multitasking (multi-task) operating system that allows you to listen to music on your phone while performing several other programs. With each application, it consumes more system memory, and when too many programs are executed at the same time, or the closed program does not release the memory correctly, the system will feel slower and even more unstable.

To solve this problem, Android introduced a new mechanism-the life cycle.

The life cycle of Android apps is managed by the Android framework, rather than by the application's direct control

System. Typically, each application (the portal is typically an activity-oncreate method), will produce

a process. When the system memory is about to be insufficient, the process is automatically recycled according to the priority level. No user or developer can determine when the application will be recycled. So in order to prevent data loss and other problems well, it is important to understand the lifecycle.

Activity life cycle:

Figure 3.1activity Life cycle diagram

Activity 4 states, 7 important methods, and 3 nested loops throughout the life cycle

1> of four states

    1. Activity (active/running) status

When the activity is running on the screen foreground (at the top of the current task's activity stack), it gets the focus to respond to the user's action, which is running, and only one moment of activity is active (active) or running

(Running) Status

    1. Pause (Paused) status

It is paused when the activity loses focus but remains visible to the user (such as when there is another transparent activity or toast, alertdialog, etc.) on top of it. Paused activity is still alive (it retains all state and member information and remains connected to the window manager), but can be killed by the system when the system memory is very small

3. Stop (Stopped) status

Is in a stopped state when it is completely obscured by another activity, and it retains all the state and member information. It is not visible to the user, but it is often killed by the system when memory is needed elsewhere

4. Inactivity (Dead) status

If the activity has not been started, has been manually terminated, or has been inactive while the system is being reclaimed, you can invoke the "Finish" method in the program to terminate the activity manually.

If it is being reclaimed by the system (according to the recycling rules based on low memory), it may be because there is not enough memory

When memory is low, the Dalvak virtual opportunity reclaims memory according to its memory recycling rules:

1. First recycle processes unrelated to other activity or service/intent Receiver (i.e. priority

activity) It is recommended that some of our (time-consuming) background operations, preferably in the form of service

2. Invisible (in stopped state) Activity

3.Service process (will be destroyed unless there is really no memory available)

4. Inactive visible (paused state) activity

5. Activity that is currently running (active/running State)

2> 7 Important methods, when the activity from one state into another state, the system will automatically call the following corresponding party

To inform users of this change

When the activity is instantiated for the first time, the system calls,

This method is called only 1 times throughout the life cycle

Typically used to initialize settings: 1, set the layout file to use for the activity 2, the button binding listener and other static settings operations

OnCreate (Bundle savedinstancestate);

When the activity is visible and the user focus does not get interactive, the system calls

OnStart ();

When activity is stopped and then restarted, the system calls

Onrestart ();

When activity is visible and the user's focus can interact, the system calls

Onresume ();

When the system launches another new activity, it must be implemented very quickly by the system call to save the persisted data in the existing activity, stop the animation, etc. before the new activity starts. After the activity has been closed by the system instead of the user's own recovery memory. The user expects that when he returns to the activity again, it remains the way it was when he left. Using Onsaveinstancestate (), the Method Onsaveinstancestate () is used to save the state before the activity is killed, triggered before OnPause (), when the system destroys the activity in order to save memory ( The user does not want to destroy this method, when the activity is instantiated again by OnCreate (Bundle savedinstancestate) will have saved temporary state data passed in because Onsaveinstancestate ( The method is not always called, the trigger condition is (press the Home key, press the power button to turn off the screen, and in both cases), you should only rewrite Onsaveinstancestate () to record the temporary state of activity, rather than persistent data. You should use OnPause () to store persistent data.

OnPause ();

Called by the system when the activity is completely overwritten by the new activity is not visible

OnStop ();

When the activity (user calls finish () or the system is destroyed by the system due to low memory) the system is called, (the entire life cycle is called only 1 times) to release the resources created in the OnCreate () method, such as the end thread, etc.

OnDestroy ();

3> 3 Nested Loops

1.Activity full life cycle: Starting from the first call to OnCreate () until the call OnDestroy () ends

2.Activity visual life cycle: from calling OnStart () to corresponding call OnStop ()

Between the two methods, you can maintain the resources needed to display the activity. If you register a broadcast receiver in OnStart () to listen for changes that affect your UI, log off in OnStop ().

3.Activity foreground life cycle: from calling Onresume () to the corresponding call to OnPause ().

To illustrate:

Example 1: There are 3 acitivity, respectively, with one,two (Transparent), three that one is the main activity when the application starts

When you start the first interface activity one, its order is

OnCreate (one)-OnStart (one)-Onresume (one)

When you click the "Open Transparent Activity" button, the order in which you go is

OnPause (one)-onCreate (double)-onStart (double)-onresume (both)

Back to the first interface, two will be killed, then the sequence of walking is

OnPause (Double)-Onactivityresult (one)-Onresume (one)-onStop (double)-OnDestroy (both)

Click on the "open Full screen Activity" button, then the sequence of walking is

OnPause (one)-onCreate (three)-OnStart (three)-Onresume (three)-OnStop (one)

Back to the first interface, three will be killed.

OnPause (three)-Onactivityresult (one)-Onrestart (one)-OnStart (one)-Onresume (one)-onStop (three)-OnDestroy (three)

Click Back to exit the app, it's in the order

OnPause (one)-onStop (one)-OnDestroy (one)

Example 2: The life cycle of the activity when the screen is switched

What is the specific life cycle when he switches:

1. Create a new activity and print out each life cycle

2, run the activity, get the following information

Oncreate-->
Onstart-->
Onresume-->

3, press CRTL+F12 switch Cheng

Onsaveinstancestate-->
Onpause-->
Onstop-->
Ondestroy-->
Oncreate-->
Onstart-->
Onrestoreinstancestate-->
Onresume-->

4, and then press CRTL+F12 to switch to vertical screen, found that two times the same log was printed

Onsaveinstancestate-->
Onpause-->
Onstop-->
Ondestroy-->
Oncreate-->
Onstart-->
Onrestoreinstancestate-->
Onresume-->
Onsaveinstancestate-->
Onpause-->
Onstop-->
Ondestroy-->
Oncreate-->
Onstart-->
Onrestoreinstancestate-->
Onresume-->

5, modify the Androidmanifest.xml, add the activity android:configchanges= "orientation", perform step 3

Onsaveinstancestate-->
Onpause-->
Onstop-->
Ondestroy-->
Oncreate-->
Onstart-->
Onrestoreinstancestate-->
Onresume-->

6, then perform step 4, found that the same information will not be printed, but more than print a line onconfigchanged

Onsaveinstancestate-->
Onpause-->
Onstop-->
Ondestroy-->
Oncreate-->
Onstart-->
Onrestoreinstancestate-->
Onresume-->
Onconfigurationchanged-->

7, change step 5 android:configchanges= "orientation" to android:configchanges= "Orientation|keyboardhidden", perform step 3, Just print onconfigchanged

Onconfigurationchanged-->

8. Perform step 4

Onconfigurationchanged-->
Onconfigurationchanged-->

Summarize:

1, do not set the activity of the android:configchanges, the screen will recall the various life cycle, cut across the screen will be executed once, cut the vertical screen will be executed twice

2, set the activity android:configchanges= "orientation", the screen will recall the various life cycle, cut horizontal, vertical screen will only be executed once

3, set the activity android:configchanges= "Orientation|keyboardhidden", the screen will not recall the various life cycle, will only execute onconfigurationchanged method


Summarize the life cycle of the activity

To add, the activity's life cycle will not change when the current activity generates an event that pops up toast and alertdialog

When the activity is running, press the home key (the same as when it is completely overwritten): onsaveinstancestate--------------OnPause to OnStop, again: Onrestart-- OnStart--->onresume

Broadcastreceive Broadcast receiver life cycle:

The life cycle is only about 10 seconds, if within onreceive () do more than 10 seconds of things, will report the ANR (Application no Response) program unresponsive error message

Its life cycle ends when the callback OnReceive () method starts and the method returns results

Service life cycle:

Figure 3.2service Life cycle diagram

Service Complete life cycle: from calling OnCreate () until the call OnDestroy () ends

There are two ways to use the service:

1> starts with call Context.startservice (), and ends with a call to Context.stopservice ()

2> is established to call the Context.bindservice () method to invoke Context.unbindservice () to close

Service-critical life cycle approach

When the user calls StartService () or Bindservice (), the first time the service is instantiated, the system invokes the method, which is called only 1 times throughout the life cycle, and is typically used to initialize the settings. Note: Calling the StartService () or Bindservice () method multiple times does not trigger the OnCreate () method multiple times

void OnCreate ()

Called by the system when the user calls StopService () or Unbindservice () to stop the service (the entire life cycle is called only 1 times) to release the resources created in the OnCreate () method

void OnDestroy ()

Services initiated through the StartService () method

The method is called by the system at the end of initialization to handle the intent object passed to StartService (). The music service will open intent to see which music will play and start playing. Note: Multiple calls to the StartService () method will trigger the OnStart () method multiple times

void OnStart (Intent Intent)

Services initiated through the Bindservice () method

The method is called by the system at the end of initialization to bind the intent object passed to Bindservice. Note: When you call Bindservice () multiple times, this method is no longer triggered if the service is started

IBinder Onbind (Intent Intent)

The system calls this method when the user calls Unbindservice (), and the Intent object is also passed to the method

Boolean onunbind (Intent Intent)

If a new client connects to the service, the new one will only call the method after the old call Onunbind ()

void Onrebind (Intent Intent)

Add : OnCreate (Bundle savedinstancestate) in conjunction with Onsaveinstancestate (bundle savedinstancestate), see the following code, To show the state before the activity was killed by the system.

    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);            if (null! = savedinstancestate) {String _userid = savedinstancestate.getstring ("strUserID");            String _uid = savedinstancestate.getstring ("Struid");            String _serverid = savedinstancestate.getstring ("Strserverid");            String _servername = savedinstancestate.getstring ("strServerName");            int _rate = Savedinstancestate.getint ("Strrate");            Updateuserid (_userid);            Updateuid (_UID);            Updateserverid (_serverid);            Updateuserserver (_servername);        Updaterate (_rate); }} @Override protected void Onsaveinstancestate (Bundle savedinstancestate) {super.onsaveinstancestate (SA        Vedinstancestate);        Savedinstancestate.putstring ("strUserID", GetUserId ());        Savedinstancestate.putstring ("Struid", Getuid ()); Savedinstancestate.putstring ("Strserverid", Getserverid ());        Savedinstancestate.putstring ("strServerName", getServerName ());    Savedinstancestate.putint ("Strrate", Getrate ()); }

Other situations that trigger activity destruction and reconstruction

In addition to the fact that the system is out of memory to destroy activity, changes in some system settings can cause activity to be destroyed and rebuilt. For example, change the screen orientation (see the example above), Change device language settings, keyboard popup, etc.

The life cycle of Android four components

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.