Discussion on the life cycle of activity in Android _android

Source: Internet
Author: User
Tags unique id

1. Full Life cycle

The graph above is the life cycle diagram of the Android activity, where the resumed, paused, stopped states are static, and the activity exists for a long time in these three states.

(1) Resumed: In this state, the user can interact with the activity, the activity at the forefront
(2) Paused: In this state, the activity is obscured by another activity, which does not accept user input information. Another activity comes to the front, translucent, but does not cover the entire screen.
(3) Stopped: In this state, the activity is completely hidden and invisible. Retains the current information and the activity does not execute any code.
(4) created and started: The system calls OnCreate () immediately after calling OnStart (), and then quickly executes Onresume ().

These are the entire lifecycle of the Android activity.

2. Main activity

The user can specify the main interface for the program to start, at which point the OnCreate () method declared as "launcher or main" activity is invoked and becomes the entry function of the program. The entry activity can define the main activity in the Androidmanifest.xml. At this point, the primary activity must use the following label declaration:

Copy Code code as follows:

<activity android:name= ". Mainactivity "android:label=" @string/app_name ">
<intent-filter>
<action android:name= "Android.intent.action.MAIN"/>
<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

3, a new example of activity

The system first invokes the OnCreate () method of the new activity, so we must implement the OnCreate () method. Such as: Declaring UI elements, defining member variables, configuring UI, and so on. But things should not be too much to avoid starting the program too long to see the interface.

Copy Code code as follows:

TextView Mtextview; Member variable to text view in the layout

@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);

Set the user interface layout for this activity
The layout file is defined in the project Res/layout/main_activity.xml
File
Setcontentview (r.layout.main_activity);

Initialize member TextView So we can manipulate it later
Mtextview = (TextView) Findviewbyid (r.id.text_message);

Make sure we ' re running on honeycomb or higher to use Actionbar APIs
if (Build.VERSION.SDK_INT >= build.version_codes. Honeycomb) {
For the main activity, make sure the app icon in the action Bar
does not behave as a button
Actionbar Actionbar = Getactionbar ();
Actionbar.sethomebuttonenabled (FALSE);
}
}

OnCreate () the OnStart () and Onresume () methods are invoked, and the activity does not stay in the created or started state.

4. Destruction of activity

The last callback to the activity is OnDestroy (), and the system performs this method as a signal that your activity will be completely removed from the system. Most apps do not need to implement this method because the references of the local class is destroyed as the activity is destroyed. And the activity should perform a clear operation of the resource in the OnPause () and OnStop () methods. If a background thread is created when the activity is OnCreate (), or if there are other resources that may cause memory leaks, you should kill them at OnDestroy ().

Copy Code code as follows:

@Override
public void OnDestroy () {
Super.ondestroy (); Always Call the Superclass

Stop method Tracing this activity started during onCreate ()
Android.os.Debug.stopMethodTracing ();
}

The system usually calls OnDestroy () after executing the OnPause () and OnStop (), unless finish () is called in OnCreate (). For example, if your activity simply makes a temporary logical jump function, it uses it to decide to jump to the next event, so that you need to call the finish () method in OnCreate (). The system will call the OnDestroy method directly, and the other lifecycle will not be executed.

5. Pause and Resume

The current activity is blocked by other visible components, the current activity is partially visible, and the current activity enters the pause state. The system calls the OnPause () method in the activity to perform the Onresume () method recovery.

If the current activity is completely blocked by another component and the current activity is completely invisible, the current activity enters the stop state.

When the system calls the OnPause () in your activity, technically, that means your activity is still partially visible. The following things are usually done in the OnPause () callback method.

(1) Stop animation or other running operations, reduce CPU waste
(2) Commit changes that have not been saved, but only content that is saved when the user leaves, such as mail
(3) Release system resources, such as broadcast receivers, sensors, GPS, or any other resources that affect power consumption.
(4) If the program is using Camera,onpause () will be a better place to release the resources of the operation.

Copy Code code as follows:

@Override
public void OnPause () {
Super.onpause (); Always Call the Superclass method

Release the Camera because we don ' t need it when paused
and other activities might need to use it.
if (Mcamera!= null) {
Mcamera.release ()
Mcamera = null;
}
}

Typically, you should not use OnPause () to save user-changed data to permanent storage, and you can store those data to permanent storage when you are sure that the changes will be automatically saved. However, you should avoid performing cpu-intensive work when OnPause (), such as writing data to DB, because he can cause switching activity to become slow. These jobs should be put in the onstop () to sit.

If the activity is actually going to stop, then reduce the amount of work in the onpause and improve fluency.

Resuming activity

The Onresume () method is invoked when the user resumes from the pause state. At this point the activity is in the foreground, including the first creation, at which time you should initialize the components that you released in the OnPause method in Onresume, and perform the initialization actions required by those activities every time they enter the resumed state.

Copy Code code as follows:

@Override
public void Onresume () {
Super.onresume (); Always Call the Superclass method

Get the Camera instance as the activity achieves full user focus
if (Mcamera = = null) {
Initializecamera (); Local method to handle camera init
}
}

6. Stop and restart activity

Proper stopping and restarting of the activity will make the user aware of the program. Some of the following scenarios involve stopping and rebooting:

(1) The user opens the menu of the recently used app and switches to another app, at which point your app is stopped, the user returns to your app, and your activity is restarted.
(2) The user launches a new activity in the app, and the current event stops after the new one is created, and if the user clicks the Back button, it restarts
(3) The user uses the app and receives the call.

The Stop State UI is not visible. The system saves activity instances in memory when the activity stops, sometimes without prior onstop (), Onrestart (), or even OnStart () methods, because most of the activity is relatively simple and the activity stops and restarts itself. All you need to do is use OnPause to stop the running action and disconnect the system resources.

The image above shows that when the user leaves your activity, the system calls OnStop () to stop the activity, the user calls Onrestart () when it returns, and then quickly calls OnStart () and Onresume (), whatever the reason causes the activity to stop , the system always calls the OnPause before OnStop

Stop the activity

When your activity calls the OnStop method, the activity is no longer visible, and all resources that are no longer needed should be released, and once your activity stops, the system destroys its instance when the activity is not needed. In extreme cases, the system kills your app process directly and does not perform the activity's OnDestroy () callback function, so you need to OnStop () to release the resource or memory leaks. Although the OnPause method is called before OnStop, you should use OnStop to perform the cpu-intensive Shut-down operation. such as writing data to DB.

When the activity is stopped, its objects are saved in memory and invoked when resume, and the system saves the current state of each view in the layout without having to initialize the components that were saved in memory before restoring to resumed state. Even if the system destroys the activity at stop, it still saves the view object's state to a bundle and restores them when the user returns to the activity.

Recreate the activity: when the activity is rotated on the screen, it is destroy and recreated. Some alternative resources, such as layout, are loaded at this time. By default, the system uses the bundle instance to hold information from each view object. To enable the Android system to restore the view state in the activity, each view must have a unique ID

To ensure additional data to saved instance state, there is an added callback function within the activity's declaration cycle, which must be rewritten onsaveinstancestate (), which will be invoked when the user leaves your activity. When the system calls this function, the system passes the bundle object when your activity is destroy, so that you can add additional information to the bundle and save it in the system. If the system wants to re-create the activity instance after the activity is destroy, the previous bundle object is passed to the Onrestoreinstancestate () method and the OnCreate () method of the activity.

Save activity State: When the activity starts to stop, the system calls Onsaveinstancestate (), so your activity can save state information by using a set of key-value pairs, which saves the state information of the activity view by default , such as the text in the EditText component or the sliding position of the ListView. To preserve additional state information for an activity, you must implement Onsaveinstancestate () and add key values to the bundle. Such as:

Copy Code code as follows:

Static final String State_score = "Playerscore";
Static final String State_level = "PlayerLevel";
...

@Override
public void Onsaveinstancestate (Bundle savedinstancestate) {
Save the user ' s current game state
Savedinstancestate.putint (State_score, Mcurrentscore);
Savedinstancestate.putint (State_level, mcurrentlevel);

Always call the "superclass so it can save" view hierarchy State
Super.onsaveinstancestate (savedinstancestate);
}

Restore activity Status: When your activity is rebuilt from the destroy, you can recover the saved state from the bundle that the system passes to your activity. Both the OnCreate () and the Onrestoreinstancestate () callback methods receive the same bundle, which contains the same instance state information. Because the OnCreate () method is invoked the first time a new activity instance is created and the instance being destroy before it is recreated, you must try to read the bundle object before checking that it is null, and if NULL, the system creates a new activity for the first time. Otherwise, the activity of being destroy is restored.

Copy Code code as follows:

protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate); Always Call the Superclass

Check whether we ' re recreating a previously destroyed instance
if (savedinstancestate!= null) {
Restore value of members from saved state
Mcurrentscore = Savedinstancestate.getint (State_score);
Mcurrentlevel = Savedinstancestate.getint (state_level);
} else {
Probably Initialize members with default values for a new instance
}
...
}

Instead of recovering the data in the OnCreate method, we can choose to implement Onrestoreinstancestate (). The Onrestoreinstancestate () method executes after the OnStart () method, which calls Onrestoreinstancestate () only if there is a state information that needs to be recovered, and therefore does not need to check whether bundle is null.

Copy Code code as follows:

public void Onrestoreinstancestate (Bundle savedinstancestate) {
Always call the superclass so it can restore the view hierarchy
Super.onrestoreinstancestate (savedinstancestate);

Restore state Saved Instance
Mcurrentscore = Savedinstancestate.getint (State_score);
Mcurrentlevel = Savedinstancestate.getint (state_level);
}

Related Article

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.