Summary of activity basics of Android four components (1)

Source: Internet
Author: User

Activity is the first thing we touch when we learn Android, and it's an essential component of Android's development process. In our Android learning, it is important to have a comprehensive understanding of the activity. I have been learning Android, the activity is also love and hate, so deliberately made a summary, hoping to those who do not understand the activity is not enough "with the shoes" some help.


Content Summary

1, the concept of Activity

2. Activity Class inheritance Relationship

3. Life cycle of Activity

4. Life cycle changes during Activity screen switching

5. Activity Start Mode

6. Communication data transfer between Activity

7. Activity Recovery and data preservation



Content Details


1, the concept of Activity

In the official Android API document given by Google, this describes the activity:

An activity is a single, focused on what the user can do. Almost all activity interacts with the user, so activity needs to focus on creating a window that can be updated with Setcontentview (int) to replace the UI view interface. Activity is often presented to the user in full-screen mode, and you can change it by setting a theme or embedding activity in other activity.


2. Activity Class inheritance Relationship

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/7E/46/wKioL1b7e4XjyHGgAAAapXglrT8046.png "title=" Class inheritance relationship for activity "alt=" Wkiol1b7e4xjyhggaaaapxglrt8046.png "/>

Through this class diagram, we can see that the activity is inherited from the Contenttextthemewrapper class, and is its immediate and only subclass.

The immediate subclasses of activity are Activitygroup, Aliasactiviyt, expandablelistactivity, and listactivity, which are commonly used in listactivity (later, the list Related usage, the relevant usage of listactivity will be spoken).



3. Life cycle of Activity

Believe this picture you have seen many times, the classics are always worth learning. Here we will learn the classics carefully.


650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M02/7E/4A/wKiom1b7gLLD3TM9AAECZvgtw8Y326.jpg "title=" Activity life cycle. jpg "alt=" wkiom1b7glld3tm9aaeczvgtw8y326.jpg "/>


All activity will implement two methods: the OnCreate () and the OnPause () method.

Here's a detailed description of each of the method details in the diagram and what the scenarios are called:

OnCreate: Create the interface here and do some initialization work on the data

OnStart: To this step becomes user visible non-interactive


Onresume: Become interactive with the user, (in the activity stack system through the stack to manage the top of these activity, run out of pop-up stack, then back to the previous activity)


OnPause: To this step is visible but not interactive, the system will stop the animation and other CPU-consuming things from the above description already know, should be here to save some of your data, because this time your program has a lower priority, it may be recalled by the system. The data that is stored here should be read in the Onresume, note: This method is done in a short time, because the next activity will not wait until this method is completed to start


OnStop: becomes invisible and is covered by the next activity


OnDestroy: This is the last method to be called before the activity is killed, perhaps the outer class calls the Finish method or the system to save space to temporarily kill it, you can use isfinishing () to judge it, If you have a progressdialog that rotates in the thread, cancel it in the OnDestroy, or the Cancel method that calls dialog will throw an exception when it ends.


Note:onpause,onstop, OnDestroy, three kinds of state activity can be killed by the system.


Normal start activity:oncreate-> OnStart, Onresume (start)

Normal exit Activity: (start), onpause-> OnStop, OnDestroy (exit)


After the activity is started, it is interrupted to enter a new full-screen activity:

(start), onpause->onstop

When recovering: Onstart->onresume


After the activity is started, it is interrupted to enter a window that is not full-screen, such as dialog:

(start), OnPause

When recovering: Onresume



4. Life cycle changes during Activity screen switching


When declaring activity in the Android program manifest, we can set the life cycle change of activity when switching between the screens and the screen, as follows:


When you do not set the activity's android:configchanges, the screen will recall each life cycle, which will be executed once when the screen is cut and executed two times when the vertical screen is cut.


When you set the activity's android:configchanges= "orientation", the life cycle is only executed once when the vertical screen is cut.


When you set the activity's android:configchanges= "Orientation|keyboardhidden", the tangent screen does not recall the declaration cycle, only the Onconfigurationchanged method is executed.



5. Activity Start Mode


We know that when we inherit an activity class, when we want to start the activity we write ourselves, we need to declare the activity that we want to start in the Androidmanifest.xml program list, while declaring the activity We can set the activity's startup mode, Launchmodel = "...", in the Android system, the activity has four startup mode, and the system is standard, the boot mode in the case of certain requirements can facilitate the system to the activity The management.


Let's talk about the different characteristics and differences of the following four startup modes:


Standard

The default mode, which can be configured without writing.

activity on the same task stack,

A new instance is created by default for each activity that is started.

Therefore, in this mode, you can have multiple identical instances, and also allow multiple identical activity overlays.


Singletop:

activity on the same task stack,

When the activity to be started is at the top of the stack, the instance that was created before the restart is repeated;

When the activity to be started is not at the top of the stack, a new instance is created


Singletask:

activity on the same task stack, only in one instance, if created will not be duplicated;

When you start an activity that is already in the stack (the activity (B) at the top of the stack jumps to activity (A) below, the activity on the A will always pop up until a.


SingleInstance:

Each activity is a standalone task stack, and only one instance of activity is placed, and the switch between the activity jumps between several different task stacks.



6. Communication data transfer between Activity


In the normal Android development process, a lot of activity interface before the need to pass the data, that is, in the activity between the need to pass the data, and how the data transmission, the transmission of what kind of data, these must have a certain understanding.

Here is a detailed description:


1, simple data using Intent to pass

A->b

Binding Data in A:

Intent Intent = new Intent (this, myreceiver.class);

Intent.putextra ("Data", "Data from A");

StartActivity (Intent);

Receive data in B:

String data = Intent.getstringextra ("Data");


2, the packet uses Bunde to pass

A->b

Binding Data in A:

Bundle B = new bundle ();

B.putstring ("string", "string data from A");

B.putint ("int", "int data from A");

B.putboolean ("Boolean", "Boolean data from A");

Intent Intent = new Intent (this, myreceiver.class);

Intent.putextra ("Datas", b);//intent.putextra (b);

Receive data in B:

Bundle B = Getintent.getextras ("datas")//b = Getintent (). Getextras ();

String datastr = b.getstring ("string", "Default");//default is the default value


3. Transfer of objects

A->b, Class User (Name,age)


1 "Serializable Java language, low efficiency

User: Inherit Serializable, class User implements Serializable

A: Intent.putextra ("User", new user ());

B: User user = (user) getintent (). Getserializableextra ("user");


2 "parcelable specifically for mobile, high efficiency

User: Inherit Parcelabe, class User implements Parcelable

Implement two methods:

public int describecontents () {return 0}

public void Writetoparcel (Parcel dest, int flags) {

Dest.writebundle ()//This can pass a lot of the same type of data

Dest.writestring (GetName ());

Dest.writeint (Getage ());

}

public static final creator<user> Creator = new Creator<user> () {

Public User Createfromparcel (Parcel source) {

Source.readbundle ();//

return new User (Source.readstring (), Source.readint ());

}


Public user[] NewArray (int size) {

return new User[size];

}

}

A: Intent.putextra ("User", new user ());

B: User user = (user) getintent (). Getparcelableextra ("user");



3. Transfer data from activated activity to main activity (return pass data)

A->b,b->a


B: Listen on return:

String bdata;

Intent Intent = new Intent ();

Intent.putextra ("Datab", bdata);

Setresult (1,intent);//Return status code can be set by itself

Finish ();


A: At startup:

Startactivityforresult (Intent, 0);//Return Request code

Implementation method: Onactivityresult (int requestcode,int resultcode,intent data)

Onactivityresult (int requestcode,int resultcode,intent data) {

if (Requestcode = = 0) {

if (ResultCode = = 1)

String s = Data.getstrignextra ("Datab");

}

}

4, there is a lazy way to pass data, to communicate, such as setting up a public class, in the public class, the data to be passed is declared as public static, so that you can communicate directly between the activity. Of course, this data can also be placed in the application of this global class. This method is usually used to determine whether the login timeout, or some global configuration, and so on.




7. Activity Recovery and data preservation

Before explaining the activity life cycle, we already knew that activity would be killed by the system in some cases, and if the activity was doing some important data, for a simple example, when we logged in one, we just filled in a part and left the interface temporarily. , when we return, if we need to re-fill in all the data, it is not a bit of a pit, that seriously affects the user experience.

Of course, this is just a small example, perhaps a bit inappropriate, but we do need to recycle the activity in the system, the activity is abnormally destroyed when the current user data, and in the re-open or restore, should be able to restore the original data.

Because the activity switch, so when the user switches back to the original activity, the original activity has two situations: one is to be recycled, one is not recycled,

The recovered a will recall the OnCreate () method, which is different from the direct start of the OnCreate () is the parameter

Savedinstancestate, not to be retracted is still onresume just fine.


Savedinstancestate is a bundle object, you can basically understand him as a system to help you maintain a map object. In OnCreate () you may use it, if the normal start oncreate will not have it, so use to determine whether it is empty.

As mentioned earlier in the life cycle, we can save the data in the OnPause method and recover the data in the Onresume method.

In fact, Google has long considered the activity of abnormal exit, the system is recovered by the data preservation and recovery-related issues.

That is the two methods: the Onsaveinstancestate (bundle outstate) and the Onrestoreinstancestate (bundle Savedinstancestate) method, the two The former is responsible for saving the data before the activity is killed abnormally, while the latter is responsible for recovering the data.


Note:

The Onsaveinstancestate () method is not invoked under normal circumstances and is called only when an activity exception occurs.

Onrestoreinstancestate () method, the system will be called, in fact, we do not need to intervene.


Let's take a look at the parameters of the Onsaveinstancestate (bundle outstate) method, yes, bundle type, remember the data passing part mentioned earlier, BUNDLD can save most of the data. Now perhaps some people say Onrestoreinstancestate () method we can not go to multi-tube, always feel the heart is not steadfast, is it, where we will outstate inside the data stored in it?

We look at OnCreate (bundle savedinstancestate), is not found what, this parameter, is also the Bundle type, in fact, here savedinstancestate is saved before the outstate, And we can cancel the previously saved data in the OnCreate method.


The final questions are summarized as follows:

Save data:

void Onsaveinstancestate (Bundle outstate) {super.onsaveinstancestate (outstate); Outstate.putlong ("id", 1234567890);}

Judging and recovering data:

void OnCreate (Bundle savedinstancestate) {.... if (savedinstancestate! = null) {...}}


Well, here we have a general understanding of the activity, and the blog is here to end. This is my first time to write about the Android article, from their own learning Android, the middle has bitter sweet, there is laughter and tears, not easy ah, today in my coming out of campus, will use Android to earn a living at the same time, write this blog, hope to be on the Android this way to go more and more wide , more and more far away.


Note: This blog is a summary type, in the middle of my own translation of the Android API, as well as some of the knowledge points are there and other articles have the same, so if there is rude or is not very appropriate place, but also ask the seniors forgive.












This article is from the "Kering" blog, make sure to keep this source http://kaiyun.blog.51cto.com/8015683/1758519

Summary of activity basics of Android four components (1)

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.