Android Learning--activity Summary

Source: Internet
Author: User

I. What IS activity

 Activity is a user interface program, in principle it provides the user with an interactive interface function. 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 put the UI on the activity-created window via the Setcontentview (View) interface, and when the activity points to a full-screen window, It can also be implemented in other ways: as a floating window (via Windowisfloating's Theme collection), or embedded in other activity (using Activitygroup). The activity is separate and is used to handle user actions. Almost all the activity has to do with the user,

"Activity"

An activity is an application component that provides a screen that users can use to interact in order to accomplish a task, such as dialing, taking pictures, sending an email, and looking at a map. Each activity is given a window on which the user interface can be drawn. Windows are usually filled with screens, but can also be smaller than the screen and float on top of other windows.

An application is usually composed of multiple activities, and they are usually loosely coupled. Typically, activity in an application is designated as "main" activity, which is presented to the user when the application is first launched. Each activity can then start another activity in order to complete a different action. Each time an activity starts, the previous activity stops, but the system retains activity on a stack ("Back stack"). When a new activity is started, it is pushed to the top of the stack to get the user focus. The back stack conforms to the simple "last in, first out" principle, so when the user finishes the current activity and then clicks the Go button, it is popped up (and destroyed) before the activity resumes.

When an activity is stopped due to a new activity initiation, it is notified that this state transitions through the activity's lifecycle callback function. There are many callback functions an activity may receive, originating from its own state change-whether the system creates it, stops it, restores it, destroys it-and each callback provides you with the opportunity to complete the specified work that fits the state. For example, when you stop, your activity should release any large object, such as a network database connection. When activity resumes, you can regain the necessary resources and restore the interrupted action. These state transitions are part of the activity's life cycle.

"Creating an Activity"

To create an activity, you must create a subclass of activity (or a subclass of the activity's subclass). In your subclass, you need to implement a callback method for the system callback, when the activity is converted in various states of its life cycle, such as when activity is created, stopped, restored, or destroyed. The two most important callback methods are:

onCreate()You have to implement this method. The system calls it when creating your activity. In your implementation, you should initialize the basic components of your activity. More importantly, this is where you have to call Setcontentview () to define the activity user interface. onPause()The system calls this method when the user leaves your activity (though not always means the activity is destroyed). This is usually when you should submit any changes that will be present beyond the user session (because the user may not be back).

There are several other life cycle callback functions that you should use in order to provide a smooth user experience, and a table operation with an abnormal interrupt can cause your activity to be interrupted or even destroyed.

1, Implementing a user interface

An activity's user interface is provided by a hierarchical view-an object that inherits from the view class. Each view controls a specific rectangular area in the activity window and responds to user interaction. For example, a view might be a button that initializes the action when the user touches it.

Android offers a number of predefined view that you can use to design and component your layouts. "Widgets" is a view that provides a visual (and interactive) element to the screen, such as a button, a file field, a check box, or just an image. "Layouts" is a view that inherits from ViewGroup and provides a special layout model for its child view, such as thread layout, grid layout, or dependency layout. You can subclass the view and ViewGroup classes (or existing subclasses) to create your own widgets and apply them to your activity layout.

The most common way is to define a layout using the View plus XML layout file saved in your program resources. In this way, you can maintain your user interface design separately, regardless of the code that defines the activity behavior. You can set the layout as UI using Setcontentview (), passing resource ID of resource layout. However, you can also create new views in your activity code and create a view hierarchy by inserting new views into viewgroup and then using that layout by passing to the root ViewGroup to Setcontentview ().

"declaring the activityin the manifest"

You must declare your activity in the manifest file in order for it to be accessible by the system. To declare your activity, open your manifest file and add a <activity> element as a sub-element of the <application> element. For example:

"Using Intent Filters"

A <activity> element can also specify multiple intent filters--using the <inetent-filter> element-to declare that other applications can activate it.

When you create a new application using the Android SDK tool, the stub activity is created automatically for you, contains a intent filter, declares the activity response "main" action, and should be placed in the "launcher" category. Intent filter looks like this.

The <action> element specifies that this is a "main" entry point for this application. The <category> element specifies that the activity should be included in the list of system applications (in order to allow the user to initiate the activity).

If you want the application to be self-contained and you do not want other applications to activate its activities, then you do not need any other intent filters. Only one activity should have a "main" action and a "launcher" category, as in the previous example. You do not want to be accessed by other applications the original activities should not have intent filters and you can start them by displaying the intent themselves.

However, if you want your activity response to be intents from other applications (and your own), then you must define additional intent filters for this activity. For each type of intent you wish to respond to, you must include the <intent-filter>, which contains the <action> element, optional, a <category> element, and/or a <data> element. These elements specify the type of intent that your activity can respond to.

"starting an Activity"

You can turn on another activity through StartActivity () and pass a intent describing the activity you want to start. Intent specifies either the activity you wish to start or describe the action you wish to complete (the operating system chooses the appropriate activity for you, possibly from a different application). A intent can transmit a small amount of data to be activated by the activity used.

Working completely within your application, you will often need to simply start an unknown activity. You can do this by creating a intent display that defines the activity that you want to start, using the class name. For example, below shows an activity how to start another activity named Signinactivity:

  

However, your application may want to perform some actions, such as sending a message, a file message, or a status update, using your activity's data. In this case, your application may not have its own activity to complete the action, so you can push the activity provided by other applications on the device to complete your action. This is where intent really counts-you can create a intent that describes the action you want to perform, and then the system launches a suitable activity from other applications. If there are multiple activities that can handle this intent, then the user can choose which one to execute. For example, if you want to allow users to send messages, you can create the following intent:

  

Extra_email additional add to intent an array of strings to specify the email address, when a mail application responds to this intent, it reads these string arrays and places them into the corresponding fields. In this case, the activity of the email application starts and when the user finishes executing, your activity resumes.

"starting an activity for a result"

Sometimes, you may want to receive a result from the activity you initiate. In this case, the activity is turned on by Startactivityforresult () (instead of startactivity ()). It then receives the result from subsequent activity, implementing the Onactiviryresult () callback function. When the subsequent activity is completed, it returns a result to your Onactivityresult () function through a intent.

For example, perhaps you want users to choose one of their contacts, so your activity can do something about the contact. Here's how you build such a intent and operation results:

This example shows the basic logic you should use in your Onactivityresult () function, in order to manipulate the results of an activity. The first condition detects if the request succeeds-if it is, then the ResultCode will be result_ok--and whether the request is the response is known-in this case, Requestcode matches the parameter of the second parameter with the Startactivityforresult (). There, the code operation activity results in a query that returns the data in the intent (parameter).

What will happen is that a Contentresolver implementation queries the content provider, returning a cursor that allows the data to be read by the query.

"Shutdown an Activity"

You can close an activity by calling its own finish () method. You can also close a separate activity before you start through Finiactivity ().

  Note : In most cases, you should not display the results of an activity using these methods. As discussed below about the activity lifecycle, the Android system manages an activity life cycle for you, so you don't need to result in your own activity. Calling these functions is harmful to the user experience and only if you do not want the user to return to the activity.

Second, activity life cycle

  

 Public classActivityextendsApplicationContext {protected voidonCreate (Bundle savedinstancestate);protected voidOnStart ();protected voidOnrestart ();protected voidOnresume ();protected voidonPause ();protected voidonStop ();protected voidOnDestroy ();}

The graph shows:

During the normal startup of an activity, these method calls are in the order of OnCreate, OnStart, and Onresume; The method sequence is OnPause, OnStop, when the activity is killed. OnDestroy, this is a complete lifecycle. Then for interrupt processing (such as the phone), it is OnPause-onStop, recovery 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 in the running of an application, it is possible to call in the phone to send in text messages, or no electricity, this time the program will be interrupted, priority to the basic function of the service phone, and the system does not allow you to occupy too much resources, At least some features (such as the phone) must be guaranteed, so when resources are low, they can be killed.

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

onCreate: Create the interface here, do some data initialization work;

OnStart: To this step becomes "user visible non-interactive" state;

Onresume: Become and user-interactive , (in the activity stack system through the stack of the activity, that is, the current activity at the top of the stack, 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. As you know from the above description, you should save some of your data here, because your program's priority is reduced and may be withdrawn by the system. The data that is stored here should be read in the Onresume.

onStop: becomes invisible and is covered by the next activity

OnDestroy: This is the last time the activity was killed before the method is called, perhaps other classes call the Finish method or the system in order to save space to temporarily kill it, you can use isfinishing () to judge it, if you have A progress dialog is running in the thread, please cancel it in OnDestroy, or else the Cancel method called dialog will throw an exception when it ends.

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

III. communication between the activity

  In Android, different Activity instances may run in a process, or they may run in different processes. So we need a special mechanism to help us deliver messages between the Activity. In Android, a message is represented by a Intent object, 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 recipient, but also the specific content. For a Intent object, the message "destination" is required, while the content is optional.

Intent is responsible for the operation of the action, the action involved in data, additional data description, Android based on this intent description, is responsible for finding the corresponding component, the intent passed to the calling component, and complete the call of the component. As a result, intent plays a role as a media intermediary, specifically providing information about the components that are called to each other, and decoupling the caller from the callee.

In the application, we can use intent in two ways:

Direct intent: Specifies the intent of the component attribute (called SetComponent (componentname) or SetClass (Context, Class). Notifies the app to launch the corresponding component by specifying a specific component class.

Indirect intent: No intent is specified for the Comonent property. 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.
For direct intent,android There is no need to parse because the target component is already clear.

What Android needs to parse is those indirect intent that, through parsing, map intent to activity, intentreceiver, or service that can handle this intent. The intent parsing mechanism is primarily to find a matching intent by locating all intentfilter in the androidmanifest.xml and the intent defined therein.

Iv.Intent Filter for Ac tivity

Intent Filter describes what kind of Intent objects a component is willing to receive, and Android abstracts it into a Android.content.IntentFilter class. In Android's androidmanifest.xml configuration file, you can specify its intent filter for an Activity via the <intent-filter > node to tell the system that the Activit Y can respond to what type of Intent.

When you use StartActivity (intent) to start another Activity, if you specify the Component property of the intent object directly, Activity Manager will attempt to start the Act specified by its Component property Ivity. Otherwise, Android will find the most matching boot from all the activity installed in the system via the other properties of Intent, and the application will get an exception thrown by the system if no suitable activity is found. The process for this match is as follows:

V. On-the-heap management of activity

Android's management of activity uses stacks, meaning that only one activity at a time is at the top of the stack, and when the activity is destroyed, the following activity is likely to float to the top of the stack, or a new activity is created, The old activity was sunk by the stack. Activity is the performance layer of the Android program. Each display screen of a program is an activity. The activity that is running is at the top of the stack and it is in the running state.

When the Activity.finish () method is called 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." Activity Manager then activates activity on the second level of the stack, pressing the original activity into 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 latter two are a group), the default is standard

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

singletop: A new instance is also sent, but a different standard is that when the requested activity is at the top of the stack (configured as singletop activity), no new instances are constructed

Singletask: and the subsequent singleinstance all create only one instance, when intent arrives, need to create the 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 send intent to it.

SingleInstance:

Starting with the concept of task, a task can be thought of as a stack that can be put into multiple activity. For example, to launch an app, Android creates a task and then launches the app's entry activity, which invokes the other activity on its interface only in this task. What if you share an activity in multiple tasks? For example, if you open a Guide service application, there is an activity is to open Google Maps, when the home button to return to the main menu and launch Google Maps app, the display is just the map, is actually the same activity, In fact, this introduces the singleinstance. SingleInstance mode is to put the activity on a separate stack, so that only this activity in this stack, different applications of the intent are received and displayed by this activity, so that the sharing. Of course, the premise is that these applications are not destroyed, so just pressed the home button, if the return key is pressed, it is not valid.

Vii. Activity's Jump

Activity jump, no return results
This is the simplest way to jump the activity. Starting another activity from one activity, direct startactivity (new Intent (current activity.this, next activity.class)).
Activity jump, return data/Results
If you need to return data or results, use Startactivityforresult (Intent Intent, int requestcode), and the value of Requestcode is custom and used 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 return! The processing function that receives the returned data/result is onactivityresult (int requestcode, int resultcode, Intent data), Here the Requestcode is Startactivityforresult Requestcode,resultcode is setresult inside of the ResultCode, the data returned inside data. * * Note that after Setresult, to call Finish () to destroy the current activity, or not return to the original activity, you cannot perform the original activity of the Onactivityresult function, See that the current activity is not responding. I am a novice, no experience, such as the discovery of errors or any good advice, please correct me! Please give me a lot of advice!

Android Learning--activity Summary

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.