Follow Google android--3.1 to tube your activity's life cycle.

Source: Internet
Author: User

As we fly through the different pages of the app, the activity in the app also transitions to different states in their respective lifecycles. When a user performs an operation that enters or leaves an activity, the Android system invokes a series of life-cycle callback functions for processing, and we can override these callback functions to allow the activity to perform the actions we want in different states.

Life Cycle callback method

Shows the life cycle of an activity and the callback method. This picture looks like a trapezoid pyramid, each of which corresponds to a life state of activity.


In these states, only the following three states are static, which can last for a period of time, and other states are transient:

resumed: in this state, the activity is in the foreground, the user can interact with it (also can be called running state, that is, the running state);

Paused: in this state, the activity part is obscured by other activity (other activity in the foreground is translucent or not filled with the entire screen), the activity in this state does not receive user input, Nor does it execute any code;

Stopped: in this state, the activity is completely hidden, the user cannot see, this state can think activity is in the background, this activity instance and its state information in this state is preserved, However, you cannot execute any code.

Both states of created and started are transient, and the system will quickly invoke the subsequent lifecycle callback method after it reaches both states, that is, the system calls OnStart () immediately after the call to OnCreate (), and then calls Onresume () immediately thereafter.

Cteate activity when the user clicks on the app icon, the system invokes the OnCreate () method that you declared as launcher (or main) activity. This activity is also the main UI portal for your app. This is also where the Android system differs from other programming modes, not by invoking the main () function to start, but by invoking different lifecycle callback methods in different life cycle states. We can define which activity will act as launcher in the Androidmanifest.xml file via Intent-filter (typically Android studio has done this for us when we created the project):
<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>
It is important to note that if either main or launcher is not defined, the app's icon will not be displayed on Android.
Whether the user clicks on an app icon in Android to open an activity or jumps to a new activity while hovering inside the app, the system creates the corresponding activity instance by calling the OnCreate () method. OnCreate () is called only once in the life cycle of an activity, so we can implement some initialization actions for UI and member variables in this method, for example:
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.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.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);}    }
Technically, the activity is visible to the user when calling OnStart ().
In summary, create a trilogy of activity: OnCreate (), OnStart (), Onresume ().
Pause & Resume Activity When an activity is partially visible and not in focus, the activity remains in the paused state. Once it is completely invisible, it becomes a stopped state. If the user returns to this activity from the paused state, the system calls the Onresume () method, which is looped as follows:
Although the system calls the OnPause () method because your activity is partially obscured, it is more common that the user will leave your app, so we should do something in this state: 1) Stop the animation or other actions that may consume the CPU in the execution; 2) Commit unsaved changes, this action only when you can confirm that the user wants the data to be saved after they leave the app (such as a text message draft), 3) release system resources, such as broadcast receivers, The operation of the sensor (such as GPS) and other resources that may be consumed by the user when paused is not needed. As an example:
@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 OnPause () we should try to do something simple and avoid doing high CPU load operations, such as writing to the database, because it slows down the speed of jumping to the next activity (we can do it in OnStop (). In paused, instances of activity are stored in memory, so we do not need to reinitialize the individual parts.
When the user resumes activity from the paused state, the system calls Onresume (). It is important to note that the system calls this method every time the activity comes to the foreground, even if the app is launched for the first time. It is precisely because of this that we need to implement the reinitialization of the components released in OnPause () in this method, and to handle the events that occur every time the resumed state is reached, for example:
@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    }}
Stop & Restart activity has several key scenarios for Stop and Restart: 1) The user opens the Recently Used Programs window, jumps from your app to another app, Your app's current activity in the foreground becomes stopped, and if the user navigates back to your app by clicking on your app icon or the "Recently Used Programs" window, the activity will start again (restart); 2) When the user navigates to a new activity in your app, the current activity stops when the new activity is created, and if the user clicks the "Back" button, the activity will start again; 3) Users receive a call on the same phone when they use the app. The process from entering stop to restart to resume is as follows:
When the activity is behind stop, the system may destroy the activity instance due to the need to recover the system memory, and in extreme cases it may not call OnDestroy () to end the app's process directly. So it is necessary for us to release resources that may leak memory in OnStop (). While we do some cleanup work in OnPause () and OnStop (), it is mentioned earlier that onPause () should do as little as possible, while OnStop () can do some high-load work. As an example:
@Overrideprotected void OnStop () {    super.onstop ();  Always call the superclass method first    //Save The note ' s draft, because the activity is stopping    //A nd we want to is sure the current note progress isn ' t lost.    Contentvalues values = new Contentvalues ();    Values.put (NotePad.Notes.COLUMN_NAME_NOTE, Getcurrentnotetext ());    Values.put (NotePad.Notes.COLUMN_NAME_TITLE, Getcurrentnotetitle ());    Getcontentresolver (). Update (            MUri,    //The URI for the note to update.            values,  //The map of column names and new values to apply to them.            NULL,    //No SELECT criteria is used.            Null     //No WHERE columns is used.            );}
The activity instance is saved in memory at the time of the stop, so we do not need to reinitialize when recovering. At the same time, the system also records the current status of each view in the layout, so if the user enters text in the input box, the content will be saved, so we do not need to store and restore them separately.

Onrestart () is called only when the activity changes from stopped to resumed state, and OnStart () is called every time the activity becomes visible (whether it's restart or the first time it's created). Therefore, some special recovery operations can be performed in Onrestart (), which is required only before the activity is stopped, not destroyed. Since all resources are basically cleared at OnStop (), it is better to use OnStart () as pairing with OnStop (), for example, when we leave the application for a long time, OnStart () is a good place to verify that the system features that the app needs are open:
 @Overrideprotected  void OnStart () {Super.onstart ();    Always call the Superclass method first//The activity was either being restarted or started for the first time So the is where we should make sure the GPS is enabled Locationmanager Locationmanager = (locationm    Anager) Getsystemservice (Context.location_service);        Boolean gpsenabled = locationmanager.isproviderenabled (Locationmanager.gps_provider); if (!gpsenabled) {//Create a dialog here this requests the user to enable GPS, and use an intent//with T He android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS ACTION//To take the user to the Settings screens to E  Nable GPS when they click "OK"}} @Overrideprotected void Onrestart () {Super.onrestart (); Always call the Superclass method first/Activity being restarted from stopped state} 
Recreate activity when the activity is destroyed because the user clicks back or the activity itself calls finish (), the system considers the activity instance to disappear forever. Because these operations indicate that no one needs the activity anymore. However, if the activity is destroyed due to system resource limitations, the system remembers its existence, and when the user returns, the system uses the data that was saved when it was destroyed to create the activity instance. The saved data used by the system to restore the previous state is called "Instance.", which is a collection of key-value pairs stored in the bundle object. Note: Each time the user rotates the screen, the activity is destroyed and rebuilt because the screen configuration changes after the screen is rotated, and the activity may have to load other resources (such as layouts, etc.). The system uses the bundle instance state by default to record the information for each view in the activity layout, so if we want to save additional activity information, we need to rewrite the onsaveinstancestate () this callback method, To add a key-value pair to the bundle object:
Static final String state_score = "Playerscore"; static final String state_level = "PlayerLevel";//... @Overridepublic 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 the view hierarchy State    super.onsaveinstancestate (savedinstancestate);}
When the activity is to be rebuilt, the system uploads the previous bundle to OnCreate () and Onrestoreinstancestate (). The difference between the two methods is that onCreate () does not check whether the bundle is null, and Onrestoreinstancestate () is called only if there is a state in the bundle that needs to be restored, so there is no need to check for null. And this method is called after OnStart (). Two ways to restore data:
@Overrideprotected void OnCreate (Bundle savedinstancestate) {    super.oncreate (savedinstancestate); The superclass first       //Check Whether we ' re recreating a previously destroyed instance    if (savedinstancestate! = N ull) {        //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    }    //...}

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);}
Destroy Activityondestroy () is the last callback function in the activity life cycle, which means that the life of the activity has come to an end. In this method we can do some cleanup work, but in fact most of the OnPause () and OnStop () have been done. It's important to note that if you have a service that runs in the background, it might consume the CPU, so it's going to end up here. In general, the system calls OnDestroy () after OnPause () and OnStop (), with one exception: when you call Finish () in the OnCreate () method, the system immediately calls OnDestroy () directly, This will not go through OnPause () and OnStop (). code example:
@Overridepublic void OnDestroy () {    Super.ondestroy ();  Always call the superclass        //Stop method tracing that the activity started during onCreate ()    android.os.Debug. Stopmethodtracing ();}

Google's official Demo

Follow Google android--3.1 to tube your activity's life cycle.

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.