Android Development--activity life Cycle Review Understanding

Source: Internet
Author: User
Tags call back

activity, like a servlet, uses a callback mechanism. We learn activity by analogy to the servlet. When a servlet is developed, the servlet runs on the Web server. When the server creates an instance of the servlet, when the Servlet method is invoked to generate a response to the user, the programmer cannot control the callback, which is the server's discretion. The activity is also developed, as long as the developer configures the activity in the Androidmanifest.xml file. When the activity is instantiated, when its method is invoked, it is completely transparent to the developer.

When developers develop a servlet, depending on the requirements scenario, it may be necessary to selectively implement the following methods:

    • Init (servletconfig config)
    • Destroy ()
    • Doget (HttpServletRequest Req,httpservletresponse resp)
    • DoPost (HttpServletRequest Req,httpservletresponse resp)
    • Sevice (HttpServletRequest Req,httpservletresponse resp
    • When a servlet is deployed to a Web application, the Web server will call the various methods above the servlet at a particular moment---called callbacks.

The return mechanism of activity is similar to this, when the activity is deployed to an Android application, as the application runs, the activity is constantly switched in different states, and the specific method in the activity is recalled----- Developers can selectively override these methods to add business-related processing . The different states of the Android run process are called lifecycles.

Android life cycle: When the activity is running in an Android app, its active state is managed by the Android runtime as an activity stack. The activity currently active is at the top of the stack.

Android Life cycle Demo: Android roughly follows four states:

    • Active Status: The current activity is in the foreground and the user is visible and can get the focus.
    • Paused: Other activity is in the foreground, the activity is still visible, but the focus is not available.
    • Stop state: The activity is not visible, loses focus
    • Destroy Reload: The activity ends, or the Dalvik process where the activity is located is ended.

Here is the life cycle diagram provided by the official API:

The following uses the code to personally test the Android life cycle, after the test is clear:

 PackageCom.lp.ecjtu.activitydemo1;ImportAndroid.os.Bundle;Importandroid.app.Activity;ImportAndroid.util.Log;ImportAndroid.view.Menu;ImportAndroid.widget.EditText; Public classMainactivityextendsActivity {Private Static FinalString TAG = "Mainactivity"; PrivateEditText EditText;//Create activity is callback@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); EditText=(EditText) Findviewbyid (R.id.edittext); LOG.E (TAG,"Start onCreate ========="); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; }    //start activity is callback@Overrideprotected voidOnStart () {//TODO auto-generated Method Stub        Super. OnStart (); LOG.E (TAG,"Start OnStart ========="); }    //Restart activity is callback@Overrideprotected voidOnrestart () {//TODO auto-generated Method Stub        Super. Onrestart ();log.e (TAG,"Start Onrestart ========="); }    //recovery Activty is callback@Overrideprotected voidOnresume () {//TODO auto-generated Method Stub        Super. Onresume (); LOG.E (TAG,"Start Onresume ========="); }    //pause activity is callback@Overrideprotected voidOnPause () {//TODO auto-generated Method Stub        Super. OnPause ();log.e (TAG,"Start onpause============="); }        //stop activity being recalled@Overrideprotected voidOnStop () {//TODO auto-generated Method Stub        Super. OnStop (); LOG.E (TAG,"Start onstop============="); }    //destroy activity is callback@Overrideprotected voidOnDestroy () {//TODO auto-generated Method Stub        Super. OnDestroy (); LOG.E (TAG,"Start ondestroy============="); }}

Run the above code: when we open the application, we call back the OnCreate ()-OnStart()-onresume() method. In the Logcat window you can see:

Back key: When we press the return key, this application or activity will end, then callback the OnPause ()-->onstop ()-->ondestroy ( ) method: In the Logcat window you can see:

Home key: When we are playing the game, suddenly came a text message, we want to see the short interest, press the Home button, and then open the application of SMS, when we press the home key activity has executed the OnPause ()-->onstop method, In the Logcat window you can see:

When we start the application, we will take the Onrestart ()-->onstart-->onresume method. In the Logcat window you can see:

By doing this, presumably we have a deep understanding of the Android activity lifecycle, and we can selectively rewrite the lifecycle approach to address some of the business needs while developing activity.

For example: The following example, when we look at the video screen, or in the registration, just fill out the user's registration information, accidentally pressed the home button, when we enter the application, found before the registration information is all gone, this time we will cry, the application to do the comparison of garbage. Under normal circumstances, the registration information we fill in is still there, that is, it is consistent with the state before we press the home button.

To understand, we use a small example to illustrate the problem:

Add EditText in the XML code code:

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:paddingbottom= "@dimen/activity_vertical_margin"Android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"Tools:context=". Mainactivity "android:orientation= "vertical">    <TextViewAndroid:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "@string/hello_activity" />    <EditTextAndroid:id= "@+id/edittext"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:ems= "Ten" /></LinearLayout>

Java code does not change, run the program, enter Peter in EditText,

Then press the home key, at the start of the mainactivity, found that the input before the content is gone.

This is obviously not a normal application and we all cry. Then we need to know the team life cycle very well, when we press the home button, the activity callback the Onpause-->onstop () method, again into the application when the callback onrestart-->onstart--> The Onresume () method shows that we can save the previous state as long as the OnPause () and Onrestart methods are processed: see the code below

 PackageCom.lp.ecjtu.activitydemo1;ImportAndroid.os.Bundle;Importandroid.app.Activity;ImportAndroid.util.Log;ImportAndroid.view.Menu;ImportAndroid.widget.EditText; Public classMainactivityextendsActivity {Private Static FinalString TAG = "Mainactivity"; PrivateEditText EditText; //defines a string string that is used to hold user input    PrivateString userstring; //Create activity is callback@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); EditText=(EditText) Findviewbyid (R.id.edittext); LOG.E (TAG,"Start onCreate ========="); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; }    //start activity is callback@Overrideprotected voidOnStart () {//TODO auto-generated Method Stub        Super. OnStart (); LOG.E (TAG,"Start OnStart ========="); }    //Restart activity is callback@Overrideprotected voidOnrestart () {//TODO auto-generated Method Stub        Super. Onrestart (); //When you start the app again, reset the value entered by the previous user EditTextEdittext.settext (userstring); LOG.E (TAG,"Start Onrestart ========="); }    //recovery Activty is callback@Overrideprotected voidOnresume () {//TODO auto-generated Method Stub        Super. Onresume (); LOG.E (TAG,"Start Onresume ========="); }    //pause activity is callback@Overrideprotected voidOnPause () {//TODO auto-generated Method Stub        Super. OnPause (); //when you press the home key, the user input string information is saved. UserString =Edittext.gettext (). toString (); LOG.E (TAG,"Start onpause============="); }        //stop activity being recalled@Overrideprotected voidOnStop () {//TODO auto-generated Method Stub        Super. OnStop (); LOG.E (TAG,"Start onstop============="); }    //destroy activity is callback@Overrideprotected voidOnDestroy () {//TODO auto-generated Method Stub        Super. OnDestroy (); LOG.E (TAG,"Start ondestroy============="); }}

Restart the app, press the Home key, enter the application OK, and look at the following diagram:

Summary: The key to understanding the life cycle is that we can selectively rewrite the life cycle methods in the development process to solve some practical problems, which is the key to the application!

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.