Four knowledge points about the activity that Android beginners must master

Source: Internet
Author: User

These days have been tinkering with the knowledge of Android, interest classes of teachers, lectures too esoteric, the day (think of what to see, after the completely do not want to listen to), and finally find out their own information in the Android learning is an important component of activity, then start!

First: Master the four states of activity and when to trigger

First of all, we need to know what activity is, simply speaking, activity is actually a screen display page. (A simple elaboration)

We know that activity is managed by the activity stack, and when it comes to a new activity, the activity is added to the top of the activity stack, and the activity is at the bottom of the activity.

There are four states in the general sense of acitivity:

1. Running state: After a new activity is launched into the stack, it is at the top of the screen, at the topmost edge of the stack, at which point it is visible and can interact with the user, and Android tries to keep it active as much as possible. Kill other activity to ensure that the active activity has sufficient resources to use. When another activity is activated, this will be paused.

2. Paused state: When activity is in this state, it remains connected to the window manager at this point, the system continues to maintain its internal state, it is still visible, but it has lost focus and therefore cannot interact with the user.

3, stopped state: When activity is not visible, activity is in stopped state. When activity is in this state, be sure to save the current data and the current UI state, otherwise the current data and UI state will be lost once activity exits or shuts down.

4, killed status: Activity was killed or was started before, in killed state. This is the activity that has been removed from the activity stack and needs to be restarted before it can be displayed and used.

Figure 1

a summary of the four states: Running States and paused states are visible, stopped state and killed state are not visible, of course starting is automatically created by the system itself, and each activity is in a certain state, for developers, is unable to control its application in a certain state, which is done by the system.

However, when the state of an activity changes, the developer can obtain the relevant notification information by calling ONXX ().

Next, let's say when the various states trigger:

  1. Running Status:

    The functions and sequences that are triggered are: onCreate ()->on Start (), Onresume ().

  Attention:

1.1:oncreate () is called only when the activity is first created, mainly responsible for the general initialization settings of the activity, including the creation of views, binding of data, and so on.

It is important to note that if a previously frozen state (that is, the system has called the Onsaveinstancestate () function on the activity), it can be restored with its Bundle parameters.

1.2:on Start () is called only when activity is becoming visible. Generally during this period you can register for a broadcast and so on.

1.3:onresume () is called when the activity is going to interact with the user, at the top of the active stack.

2. Paused Status:

Functions and sequences that are triggered by the running state to the paused state are: Onresume (), onpuased ()

The functions and order of the paused state reverting to the running state are: onpuased (), Onresume ().    

Note:   
2.1:onpuased () is called when an activity loses the system focus, including a partial occlusion of the meeting, and the device goes into hibernation, and so on. In general, some unsaved data is persisted during this period and other CPU-intensive operations are stopped, and the system UI thread is blocked because of the time-consuming operation.

2.2: An activity that is in a paused state is forced to end by the system only if the system is extremely short of memory resources.

3.stopped status:

The function and order triggered by the paused state to the stop State is: onpuased (), on Stop ().
The function and order that the stop state reverts to the running state is: on Stop (), Onrestart (), on Start (), Onresume ().

Note:    
3.1:on Stop () is called when an activity becomes invisible, possibly because the activity is being written off or a new activity completely obscures the activity. During this time, it is generally possible to unregister the broadcast, and so the user is not visible.
3.2:onrestart () is a priority call when an activity resumes from a stopped state to a running state.

 4. Killed Status:

The stop state to the death state is divided into two situations: (1) caused by user action, then execution: on Stop (), OnDestroy ().

(2) The activity is forcibly terminated by automatic enforcement by the system.

Note:    
4.1:ondestroy () is called when an activity is being finished by the system.

The above is about the activity of the four states and when the detailed decomposition of the trigger, of course, if there is any wrong or questions can message or email [email protected] Thanks!

Second: Mastering the activity's life cycle and the event name and number of triggers triggered at each stage

The activity has a total of seven life cycle functions, OnCreate (), Onrestart (), on Start (), Onreusme (), OnPause (), and on Stop (), Ondestory ().

1:oncreate ()

When Acitivity is first created, the things that are typically done here include creating a View (Setcontentview ()), populating the view with the necessary data, and so on.

2:onrestart ()

If the activity has been stopped before, the next OnStart () method will trigger this method, which is triggered when the event in the stop state needs to be presented to the user again.

3:onstart ()

As long as the activity is not visible and visible, it triggers this method, but is not included in the case of Alertdialog occlusion/display.

4:onresume ()

This method is triggered when activity comes to the top, that is, when you start interacting directly with the user. For example, when the activity is obscured by a alertdialog, the Onresume () method is triggered when the alertdialog disappears.

5:onpause ()

The triggering condition of the same onresume () is just the opposite, and if the activity is at the top, it will be triggered when it wants to yield the topmost position.

OnPause () and Onresume () are the two most frequently triggered methods, so there should be no way to consume resources too much.

6:onstop ()

This method is triggered when an activity no longer needs to be presented to the user. If the memory is tight, the system will end the activity directly without triggering the OnStop method.

So saving state information should be done at onpause time, not onstop. Activities that are not running in the foreground will be stopped or the Linux management process can end these activities at any time in order to reserve enough storage space for the new activity. Therefore, it is important for developers to always keep this principle in mind when designing applications. In some cases, the OnPause method may be the last method of activity triggering, so developers need to save the information at this time.

7:ondestroy ()

This method is triggered when the activity is destroyed. As with the OnStop method, if the memory is tight, the system will end the activity directly without triggering the method.

Next we use the code to implement the specific method trigger:

Create an Android project and edit it in mainactivity

public class Mainactivity extends Activity {//OnCreate system automatically initialized @Override protected void OnCreate (Bundle save        Dinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    LOG.I ("--mainactivity--", "--------automatic initialization---------of the oncreate-system");        }//From stop to active state @Override protected void Onrestart () {Super.onrestart () is executed;    LOG.I ("--mainactivity--", "------execution----When the onrestart--stop becomes active"); //activity is executed when the event starts loading (when it is newly created, or when it is restarted!)        ) @Override protected void OnStart () {Super.onstart ();    LOG.I ("--mainactivity--", "--------OnStart execute-----When loading events---)";        The//activity is restored to the active state (any time it enters the activation state will be executed) @Override protected void Onresume () {super.onresume ();    LOG.I ("--mainactivity--", "----------onresume-perform-------------when resuming to Active state");        }//activity is overwritten when executed @Override protected void OnStop () {super.onstop (); LOG.I ("--mainactivity--", "-------onstop----be overwritten-----------");        //activity is executed when exiting or being reclaimed, only once @Override protected void OnDestroy () {Super.ondestroy ();    LOG.I ("--mainactivity--", "---------OnDestroy executed when the---exits or is recycled, executes only once--------------"); }}

When we start the deployment program, we use the Logcat log to view the information

The above is about mastering the life cycle of activity and the event name and number of triggers triggered at each stage

Third: Mastering how the values are passed between the various forms in the activity

As we know the activity is a form of the page display, since it is the page display, then we need to display data and read data, then the question is, how the activity in the various forms to pass the value.

Here's a keyword: Intent: In Android, the Intent object is responsible for switching between the activity windows, and he is also tasked with transmitting data.

Next we use the code to implement the analysis concretely (using tool Eclipse):

First: First we create an Android project named Activityvalue and in the SRC directory, respectively, create the name: secondactivity Java generic class, second_oneactivity Java Common class inherit activity respectively

   

Create a layout XML file that corresponds to Secondactivity, second_oneactivity, respectively, in the catalog layout

Name is: Activity_second_one.xml

Name is: Activity_second.xml

Next we'll edit in the Secondactivity.java file:

Package Com.example.activityvalue;import Java.util.arraylist;import Com.example.activitylife.r;import Com.example.activityvalue.second_oneactivity;import Android.app.activity;import Android.content.Intent;import Android.os.bundle;import Android.view.view;public class Secondactivity extends activity{@Override protected void on        Create (Bundle savedinstancestate) {super.oncreate (savedinstancestate);    Statement Activity Setcontentview (R.layout.activity_second); }//Pass a normal value to a form public void mytestone (view view) {System.out.println ("================= passes a normal value to a form =====        ================");        Intent Intent = new Intent (this,second_oneactivity.class);        The value of the form Intent.putextra ("Stuname", "Xi Big");        Intent.putextra ("Stuage", 20);        Intent.putextra ("Ismerry", false);        Set array Intent.putextra ("Stuhobby", New string[]{"basketball", "Badminton", "soccer"});        Sets the collection value arraylist<string> list = new arraylist<string> (); LiSt.add ("Beijing");        List.add ("Guangdong");        List.add ("The United States");        Set the value to intent in Intent.putstringarraylistextra ("Stucitys", list);    Activate activity startactivity (intent); }    }

We first deploy in the Secondactivity file the data we need to remove different types of data m, from the above we know that we are passing values through the intent

To edit in Second_oneactivity:

 1 package com.example.activiyvalue; 2 3 Import Java.lang.reflect.Array; 4 Import java.util.ArrayList; 5 Import Java.util.Arrays; 6 7 Import android.app.Activity; 8 Import android.content.Intent;     9 Import android.os.bundle;10 Import android.widget.textview;11 public class Second_oneactivity extends activity{13         + Private TextView showtext;15 @Override17 protected void onCreate (Bundle savedinstancestate) {18 Super.oncreate (savedinstancestate); 19 20//Declare a layout file of Setcontentview (R.layout.activity_second_one         ); 22 23//Remove the transmitted data from Intent Intent Intent = Getintent (); 25 26//Remove Normal data 27 String name = Intent.getstringextra ("Stuname"); int = Intent.getintextra ("Stuage", 0); Smerry = Intent.getbooleanextra ("Ismerry", false); 30 31//Remove array data string[] Hobbys = Intent.getstri Ngarrayextra ("Stuhobby"); String hobby = arrays.tostring (hobBys); 34 35//Remove ArrayList collection data arraylist<string> citys =intent.getstringarraylistextra ("Stu Citys "); PNs String city = arrays.tostring (Citys.toarray ()); 38 39//declaration ACTIVITY40 Showtext = (TextView) Findviewbyid (R.id.showtext); 41 42//Dynamically add text content in activity. String str = "Name:" +name+ ", Age: "+age+" \ n "+44" Marriage No: "+ismerry+" \ n "+45" hobby: "+hobby+" \ n "+46" city : "+city;47 showtext.settext (str); 48 49 50 51}

If a layout file is declared as an error on line 21st, there is no auto-generated handle in the R file we can do that.

Right-click on the project to reload the project to:

  

Next we will declare the activity class file in the Androidmainifest.xml in the project directory

In the premise of the declaration, we set the string parameter first.

Next, start declaring in Androidmainifest.xml.

Next, go back to Mainactivity.java. Define a method for jumping activity

1     //============================ Open a case of a form pass value ==============================2 public     void Setvaluesmydemo ( View view) {3         Intent Intent = new Intent (this,secondactivity.class);  Create an Activity Object 4         //Start activation activity status is START5         startactivity (Intent); 6     }

Define a button in the Activity_main.xml layout file

1 <button2 android:id= "@+id/button1" 3 android:layout_width= "match_parent" 4 android:layout_height= "Wrap_content" 5 android:text= "Activity form Pass value case" 6 android:onclick= "Setvaluesmydemo"/>

Button binding a method corresponds to the Setvaluesmydemo method in the Mainactivity.java

The next activity in the Setvaluesmydemo method is called the Secondactivity.java corresponding layout file

Then we're going to add a button to the Secondactivity.java corresponding layout file activity_second.xml.

<button        android:layout_width= "match_parent"        android:layout_height= "wrap_content"        android:text= " Pass ordinary data "         android:onclick=" Mytestone "/>" through intent

The method of clicking Event Binding in Activity_second.xml is the corresponding Mytestone method in the Secondactivity.java file:

The next activity called in the Mytestone method is Second_oneactivity.java we read the data in this file and set the value in the Secondactivity.java file.

Next witness the miracle moment: We run our program, open our emulator or the real machine deployment file

Click the button in the form to enter the secondactivity layout file (this is where the page jumps)

On the Secondactivity page we are setting the values so when we click again we will be reading the data in the Second_oneactivity layout file.

Click Show Jump below:

  

Summary: It is known from the case that the jump between activity and activity is the value of the transfer between activity and activity through the call of the previous activity to the next activity, where the method of intent object is very important, The task of jumping and passing values!

Third: Master Activity form State Save problem

Here's how to save the current form state in our code to achieve:

On top of our case, there are two ways to rewrite activity in the Mainactivity.java file:

Onrestoreinstancestate (Bundle savedinstancestate)
    ======================== form state Save and restore ====================================        @Override        protected void Onrestoreinstancestate (Bundle savedinstancestate) {            super.onrestoreinstancestate (savedinstancestate);            Recovery status            if (savedinstancestate!=null) {                String msg = savedinstancestate.getstring ("message");                Set this data to the desired place                Toast.maketext (this, "previous message:" +msg, 50000). Show ();            }        }

Onsaveinstancestate (Bundle outstate)

======================== saved state ====================================        @Override        protected void Onsaveinstancestate (Bundle outstate) {            //TODO auto-generated method Stub            super.onsaveinstancestate (Outstate );            Save Data            outstate.putstring ("message", "hello!");            Toast.maketext (This, "state has been saved!") ",". Show ();        }

After we have finished, we start to run the program with the final result as follows:

  

Summary: The above is through the other teachers of a data and cases themselves summed up four knowledge points, for Android entry-level players such as me, you can take to try, there is a sense of accomplishment, of course, above the operation of the problem or welcome the great God came to patronize, hope that continuous progress it. Come on.

Four knowledge points about the activity that Android beginners must master

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.