4. Life cycle activity of Android activity

Source: Internet
Author: User

1. Full Life cycle

is the life cycle diagram of the Android activity, where the resumed, Paused, stopped states are static, and the activity in these three states has a long time.

(1) Resumed: In this state, the user can interact with the activity at the front

(2) Paused: In this state, activity is obscured by another activity, and the activity is not acceptable for user input information. The other activity comes to the front, translucent, but does not cover the entire screen.

(3) Stopped: When in this state, the activity is completely hidden and not visible. Keep the current information, activity does not execute any code.

(4) created and started: Call OnStart () quickly after the system calls OnCreate (), and then execute Onresume () quickly.

The above is the entire life cycle of Android activity.

2. Main activity

The user can specify the main interface that the program launches, at which point the OnCreate () method declared as "launcher or main" activity is called 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 be declared with the following label:

<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.aNew instance 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 the UI, and so on. But things don't have to be too much to start the program too long to see the interface.

TextView Mtextview; Member variable for text view in the Layout@overridepublic void OnCreate (Bundle savedinstancestate) {    super.oncreat E (savedinstancestate);    Set the user interface layout for this Activity    //The layout file was defined in the project Res/layout/main_activi Ty.xmlfile    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.versio N_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 () calls the OnStart () and Onresume () methods after execution, and the activity does not stop in the created or started state.


4. Destruction of activity

The last callback for the activity is OnDestroy (), which performs this method as a signal for your activity to 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 activity should perform a clear operation of activity resources in the OnPause () and OnStop () methods. If you create a background thread in OnCreate (), or other resources that might cause memory leaks, you should kill them at OnDestroy ().

@Overridepublic void OnDestroy () {    Super.ondestroy ();  Always call the superclass    //Stop method tracing that the activity started during onCreate ()    android.os.Debug. Stopmethodtracing ();}
The system is typically executed with OnPause () and OnStop () after calling OnDestroy (), unless the finish () is called in OnCreate (). For example, if your activity just does a temporary logical jump function, it uses it to decide to jump to the next activity, so you need to call the finish () method in OnCreate (). The system will call the OnDestroy method directly, and the other life cycles will not be executed.

5. Pause and ResumeThe current activity is blocked by other visible components, the current activity part is visible, the current activity enters the pause state. The system invokes the OnPause () method in activity and performs the Onresume () method recovery.The active activity is completely blocked by other components and the current activity is completely invisible, then the current activity enters the stop state.
When the system calls the OnPause () in your activity, technically, that means your activity is still in a partially visible state. Usually in the OnPause () callback method, do the following things.(1) Stop the animation or other running operations to reduce CPU waste(2) Submit unsaved changes, 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 resource that affects power.(4) If the program is using Camera,onpause () it will be a better place to release the resources.
@Overridepublic void OnPause () {    super.onpause ();  Always call the superclass method first    //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;}    }
In general, you should not use OnPause () to store user-changed data on permanent storage, and when you confirm that users expect those changes to be saved automatically, you can save those data to permanent storage. However, you should avoid performing cpu-intensive work at OnPause (), such as writing data to DB, because he can cause the switch activity to become slow. The work should be put into the onstop () to sit.If the activity is actually going to be stop, then the workload in OnPause should be reduced to improve fluency.Resume ActivityThe Onresume () method is called when the user resumes from the pause state. At this point the activity is in the foreground, including the first time it is created, you should initialize the components that you freed in the OnPause method in Onresume and perform the initialization actions that the activity requires each time it enters the resumed state.
@Overridepublic void Onresume () {    super.onresume ();  Always call the superclass method first    //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 activityProper stop and restart activity will make the user aware of the program. Some of the following scenarios involve stopping and restarting:(1) The user opens the menu of the most recently used app and switches to another app, at which point your app is stopped and the user returns to your app, then your activity is restarted.(2) The user initiates a new activity operation in the app, the current activity will stop after the new activity is created, and if the user clicks the Back button to return to the previous activity, restart(3) The user uses the app, when receiving a call.The Stop State UI is not visible. The system saves activity instances in memory when activity is stopped, sometimes without prior onstop (), Onrestart (), or even OnStart () methods, because most activity is relatively simple and activity stops and restarts itself. You only need to use OnPause to stop the running action and disconnect the system resources.Show: When the user leaves your activity, the system calls OnStop () to stop the activity, call Onrestart () when the user returns, and then quickly call OnStart () and Onresume (), whatever causes the activity to stop, The system always calls OnPause before OnStopStop activityWhen your activity calls the OnStop method, the activity is no longer visible, and all resources that are no longer needed should be freed, and once your activity is stopped, the system will destroy its instances when the activity is not needed. In extreme cases, the system kills your app directly and does not perform the activity's OnDestroy () callback function, so you need to release resources in OnStop (), or memory leaks. Although the OnPause method is called before OnStop, you should use OnStop to perform cpu-intensive shut-down operations. such as writing data to DB.When activity is stopped, its objects are saved in memory and re-invoked at resume, without having to initialize those stored in memory before reverting to the resumed state, the system saves us the current state of each view in the layout. Even if the activity is destroyed at activity stop, it will still save the view object's state to a bundle and restore them when the user returns to the activity.

Recreate activity: When 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 a bundle instance to hold information from each view object. Each view must have a unique ID for the Android system to be able to restore the view state in the activity.
To ensure additional data to saved instance state, there is an added callback function in the activity's declaration cycle, which must be rewritten onsaveinstancestate (), which is called 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 recreate the activity instance after the activity is destroy, the previous bundle object is passed to the activity's Onrestoreinstancestate () method and the OnCreate () method.

SaveActivity state: When the activity starts stop, the system calls Onsaveinstancestate (), so your activity can save state information by using a collection of key-value pairs, which will save state information for the activity view by default. For example, the text in the EditText component or the sliding position of the ListView. In order to save additional state information for the activity, you must implement Onsaveinstancestate () and increment the key-value pair into the bundle. Such as:
Static final String state_score = "Playerscore"; static final String state_level = "PlayerLevel"; @Overridepublic void on Saveinstancestate (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 the view hierarchy State    super.onsaveinstancestate (savedinstancestate);}

RecoveryActivity status: When your activity is rebuilt from destroy, you can restore 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 that was destroy before it is recreated, you must try to read the bundle object before checking whether it is null, and if NULL, the system creates a new activity for the first time. Otherwise, the activity is resumed by destroy.
protected void OnCreate (Bundle savedinstancestate) {    super.oncreate (savedinstancestate);  Superclass first    //Check Whether we ' re recreating a previously destroyed instance    if (savedinstancestate! = null) {        //Restore value of 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 data in the OnCreate method, we can choose to implement Onrestoreinstancestate (). The Onrestoreinstancestate () method executes after the OnStart () method, and the system only calls Onrestoreinstancestate () when there is state information that needs to be restored, so you do not need to check if the bundle is null.
public void Onrestoreinstancestate (Bundle savedinstancestate) {    //All call the superclass so it can restore the VI EW hierarchy    super.onrestoreinstancestate (savedinstancestate);    Restore State members from saved instance    Mcurrentscore = Savedinstancestate.getint (state_score);    Mcurrentlevel = Savedinstancestate.getint (state_level);}

4. Life cycle activity of Android 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.