Android Activity Learning Notes _android

Source: Internet
Author: User

First, what is the activity

Activity is a user interface program, which in principle provides a user with an interactive interface. It is the basic functional unit of an Android application. The activity itself has no interface. So the activity class creates a window where the developer can place the UI on the window where the activity is created, and when the activity points to the Full-screen window, the Setcontentview It can also be implemented in other ways: as a floating window (through a windowisfloating collection of topics), or embedded in another activity (using Activitygroup). The activity is separate and is used to handle user actions. Almost all activity has to do with the user,

Second, activity life cycle

  

public class activity extends ApplicationContext {

protected void onCreate (Bundle savedinstancestate);
 
protected void OnStart ();
 
protected void Onrestart ();
 
protected void Onresume ();
 
protected void OnPause ();
 
protected void OnStop ();
 
protected void OnDestroy ();

}

I believe many friends have seen this flow chart, but also the basic understanding of the activity of the life cycle of several processes, we have to say that these several processes.
1. Start activity: The system calls the OnCreate method first, then calls the OnStart method, and finally invokes the onresume,activity into the running state.
2. Current activity is covered or locked by other activity: The system calls the OnPause method to suspend execution of the current activity.
3. Current activity by the covered state back to the foreground or unlock screen: The system will call the Onresume method, again into the running state.
4. Current activity moves to the new activity interface or presses the home key back to the main screen, which itself is relegated to the background: The system calls the OnPause method first, then calls the OnStop method and goes to a standstill state.
5. The user goes back to this activity: the system calls the Onrestart method first, then calls the OnStart method, and finally calls the Onresume method, which goes into the running state again.
6. The current activity is in the covered state or the background is not visible, that is, steps 2nd and 4th, the system is out of memory, killing the current activity, and then the user returns to the current activity: Call OnCreate method, OnStart method, Onresume method into the running state.
7. User exits Current activity: The system first calls the OnPause method, then calls the OnStop method, and finally calls the Ondestory method, ending the current activity.
As the diagram shows:

In the normal start-up of an activity, these method calls are in the order of OnCreate-> OnStart-> onresume; The method sequence is OnPause-> onStop when the activity is killed OnDestroy, this is a complete lifecycle. Then for interrupt processing (such as a call), it is OnPause-> onStop, OnStart-> onresume If the current application is a theme (translucent) or translucent Activity so interrupted is onpause, recovery time onresume.

Then for "Other app need Memory", is our mobile phone when running an application, it is possible to call in the phone to send in a text message, or no electricity, this time the program will be interrupted, priority to serve the basic functions of the phone, the other system does not allow you to occupy too much resources, At least some features (such as telephones) are guaranteed, so there is a risk of being killed when there is insufficient resources.

The role of the method in the system and what we should do:

OnCreate: Create an interface here, do some data initialization work;

OnStart: To this step into the "user visibility is not interactive" state;

Onresume: To become interactive with the user (the activity stack system manages these activity through stacks, that is, the current activity is at the top of the stack, running the 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. As you can see from the above description, you should save some of your data here, because your program's priorities are lowered at this time and may be retrieved by the system. The data stored here should be read in the Onresume.

OnStop: Become invisible, covered by the next activity

OnDestroy: This is the last called method before the activity is killed, possibly other classes call the Finish method or the system to save space to temporarily kill it, you can use isfinishing () to judge it, if you have a progress dialog in a thread, please cancel it in the OnDestroy, otherwise the Cancel method that calls dialog will throw an exception when the threads end.

Onpause,onstop,ondestroy, in three different states, activity can be killed by the system.

III. communication between the activity

In Android, different activity instances may run in one process or in different processes. So we need a special mechanism to help us pass messages between the activity. Android uses a Intent object to represent a message, a Intent object that contains not only the destination of the message, but also the content of the message, which is like an email, which should include not only the address of the Inbox, but also the specific content. For a Intent object, the message "destination" is required and the content is optional.

Intent is responsible for the operation of the action, action involved in data, additional data description, Android according to this intent description, responsible for finding the corresponding components, the intent passed to the calling component, and complete the component calls. Therefore, intent plays a role as a media intermediary, which provides information about the invocation of components to each other, and realizes the decoupling between the caller and the callee.

In applications, we can use intent in two ways:

Direct intent: Specifies the intent of the component property (called SetComponent (componentname) or setclass (context, Class). Notifies the application to start the corresponding component by specifying a specific component class.

Indirect intent: Intent with no comonent attribute specified. These intent need to contain enough information so that the system can determine the components that meet this intent in all available components based on this information.
There is no need to parse the direct intent,android because the target component is already clear.

What Android needs to parse is those indirect intent, which, by parsing, maps intent to activity, intentreceiver, or service that can handle the intent. The intent resolution mechanism is to finally find a matching intent by looking up all the intentfilter that have been registered in Androidmanifest.xml and the intent defined therein.

Iv. activity of Intent Filter

Intent Filter describes what kind of Intent object a component is willing to receive, and Android abstracts it into Android.content.IntentFilter classes. In the Android androidmanifest.xml configuration file, you can specify its intent filter for an activity through the <intent-filter > node to tell the system what type of activity can respond to of Intent.

When you use StartActivity (intent) to start another activity, if you specify the Component property of the intent object directly, the activity Manager attempts to start its Component property-specified ACT Ivity. Otherwise, Android will look for a startup with the best match from all the activity installed in the system through other attributes of Intent, and if no suitable activity is found, the application will get an exception thrown by the system. This matching process is as follows:

V. The stack management of activity

Android uses stacks for activity management, which means that only one activity at a time is at the top of the stack, and when the activity is destroyed, the following activity can float to the top of the stack, or a new activity is created, Then the old activity was sunk by the pressure stack. Activity is the performance layer of the Android program. Each display screen of the program is an activity. The running activity is at the top of the stack and it is running.

When the Activity.finish () method is invoked in a program, the result is the same as when the user presses the back key: It tells the activity manager that the activity instance can be "recycled." The activity Manager then activates the second layer of the stack, which presses the original to the second layer of the stack, from the Running state to the paused state.

Vi. Loading mode of activity

Standard, Singletop, Singletask, SingleInstance (where the first two are a group, the last two are a group), the default is standard

Standard: That is, the intent will be sent to the new instance, so each jump will generate a new activity.

singletop: It is also sending new instances, but the point of different standard is that when the requested activity is at the top of the stack (configured to singletop activity), no new instances are constructed

singletask: And later singleinstance all create only one instance, and when intent arrives, you need to create an activity that is set to Singletask. The system checks to see if an instance of the activity is already in the stack. If there is a direct intent sent to it.

singleinstance:

First, the concept of task, which can be considered a stack, can be put into multiple activity. For example, if you start an application, Android creates a task and then launches the application's entry activity, which calls other activity on its interface only in this task. What if you share an activity in multiple tasks? For example, if you open a tour guide service class application, there is an activity is to open the Google Map, when the home key back to the main menu and launch the Google Map application, the show is just the map, is actually the same activity, In fact, this introduces singleinstance. SingleInstance mode is to put the activity into a stack, so that only this activity in the stack, the different applications of intent are received and displayed by the activity, so that the share. Of course, the premise is that these applications have not been destroyed, so just pressed the home key, if pressed the return key, it is invalid.

Vii. the activity Jumps

Activity jump, no return result
This is the simplest activity to jump the way. Start another activity from one activity, direct startactivity (new Intent (current activity.this, next activity.class)).
Activity jumps, returning data/results
If you need to return data or results, use Startactivityforresult (Intent Intent, int requestcode), and the Requestcode value is customized to identify the target activity of the jump. The target activity of the jump is to return the data/result, setresult (int resultcode) returns only the result without data, or setresult (int resultcode, Intent data) both returns! The processing function for receiving the returned data/results is onactivityresult (int requestcode, int resultcode, Intent data), Here the Requestcode is Startactivityforresult Requestcode,resultcode is setresult inside ResultCode, the returned data inside.
* * Note, after Setresult, to call Finish () to destroy the current activity, otherwise can not return to the original activity, you can not perform the original activity of the Onactivityresult function, See the current activity is not responding.

Viii. Examples of activity switching

Each activity in Android typically describes all of the screens on a screen (except for window-level activity), so switching between the two interfaces of the phone screen (or, more accurately, the entire screen) involves activity switching.
Assuming there are two activity, respectively, ACTIVITY01 and Activity02, there is now a button in the Activity01 page that will switch to Activity02 after the click. And when the activity is switched, Activity01 passed a parameter to the Activity02. (Intent can be used when switching activity, and can pass data.)

How do you do it? General ideas for:

1. Set a trigger space in the ACTIVITY01 and add a trigger

2. Add listener to the ACTIVITY01 trigger

3. In the Listener interface implementation, set up a intent that allows the intent to bind Activity01 and Activity02, and store the values to be transferred in the Putextra object by intent

3.listener interface implementation end, invoke this intent object through ACTIVITY01 launch, switch to ACTIVITY02

4. In Activity02, use getintent to get the intent object instance in the context switch that makes itself start

5. Use the Getstringextra to get the value of the previous Putextra by obtaining an instance of the intent object.

Of course, if you have a better understanding of intent later, you need to choose a more appropriate function to store the data and get the data according to the actual situation.

Here's a demo of the implementation:

Finally, attach the key section code:

In Activity01:

Button.setonclicklistener (New Button.onclicklistener () {//More accurate should be view.onclicklistener public
 void OnClick (View V)
 {
  /* Create a new Intent object *
  /Intent Intent = new Intent ();
  Intent.putextra ("name", "Leipei"); 
  /* Specify intent to start class * *
  Intent.setclass (activity01.this, activity02.class);
  /* Start a new activity
  /Activity01.this.startActivity (intent);
  /* Close the current Activity
  /Activity01.this.finish ();
 }
);

In Activity02:

 String Name=intent.getstringextra ("name");
 Textview2.settext ("Activity01 passed the value of:" +name);

The above is a small compilation of the activity involved in the knowledge point, I hope to help you learn, there are many missing knowledge, small series will continue to improve the supplementary, I hope you continue to pay attention.

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.