"Android Official document" translation Android Official document-activities (i)

Source: Internet
Author: User

Activity is a program component that can provide user interaction, such as making a phone call, taking pictures, sending an email, or displaying a map. Usually the window fills the screen, but it can be smaller or suspended at the top of the window than the screen.

Apps are usually made up of multiple activities that support mutual jumps. In general, each activity is unique in the application, as if the primary activity is the first activity applied, and other activity can be started by other actions. When a new activity is started, the old activity is stopped, but the activity is saved to the stack. When a new activity is started, the activity is put into the stack and the operation gets the focus, and when the user completes the current activity operation or fallback operation, the activity is taken out of the stack and the activity before the stack is started again.

When an activity is paused due to the start of a new activity, a change in state is notified through the activity's lifecycle callback method. Activity through the system's callback method, to create, destroy, stop, restore it. When activity stops, objects need to be freed, such as network operations or database operations. When activity resumes, you can regain access to the required resources and input actions. These state transitions are part of the life cycle.

Other parts of this blog will explore how to build and use activity knowledge. Including the activity life cycle discussion, can help you to manage various activity state transitions.

Create an Activity
To create an activity, you need to create a subclass of activity (or a subclass that already exists). In your subclass, you need to execute a callback method to implement an active transition between the states of its life cycle. For example, activity creation, stop, restore, or destroy, here are two very important callback methods:

OnCreate()

This method has to be implemented, and when the activity is created, the system calls this method, in which we can initialize some important components. The heavy priority is that you need to call the Setcontentview () method to define a layout for the activity

OnPause()

When you leave the current activity, this method is called, note: Leaving the activity means more than just destroying the activity. (Can be simply overridden when a actvity is also called)

Activity also has several other life cycle callback methods that we should use to achieve a smooth user experience between activities, while handling bursts of interruptions that cause your activity to be stopped or even destroyed. All life-cycle callback methods are discussed later.

implementing the user interface
The user interface of an activity is provided by the hierarchy of view objects that are derived from the views graph class. Each view controls a specific rectangular space in the active window and can respond to user interaction. For example, a button that responds to an action when the user touches it.

Android provides some of the existing view that we can use to design and organize the interface we want. A part is a visual (interactive) screen element, such as a button, text display control, check box, or just a picture. "Layouts" belongs to ViewGroup and can provide a unique layout, such as a linear layout, a grid layout, or a relative layout. You can also inherit the view and ViewGroup classes (or existing subclasses) to create your own widgets and layouts and apply them to your activity layout.

The most common approach is to build our layout in an XML layout file and save it in the application's path. In this way, you can maintain the design of the user interface in the source code to define the behavior of the activity in this layout. We use Setcontentview () to set the layout for the activity, which is set by the original ID to point to the layout file. However, we can also create a new view in the activity's code.

For information about creating a user interface, see the user interface documentation.

declaring activity in a configuration file
If you want the system to be accessible, you need to declare the activity in the configuration file. Open your profile and declare it as follows:

... >  ... >      <activity android:name=".ExampleActivity" />      ...  ... >  ...</manifest >

Here are a few other properties that you can define, such as the active label, icon, or theme, to set the user interface for the theme. Android: The Name property is the only property that specifies the class name of the activity. Once you post your application, you should not change this name, because if you do, you may break some features, such as application shortcuts.

Using Intent Filters
Elements can also use the < intent filter > element to specify various intent filters to declare how other application components activate it.

When you use the Android SDK to create a new app, a short activity will automatically create a intent filter for you that includes declaring the active response "main" role, which should be placed in the "Start" category. The intent filter is as follows:

<activity  android:name  = ". Exampleactivity " android:icon  =" @drawable/        App_icon ";  <intent-filter ;  <action  android:name  = "Android.intent.action.MAIN" />  << Span class= "Hljs-title" >category  android:name  =  "Android.intent.category.LAUNCHER" />  </< Span class= "Hljs-title" >intent-filter ;  </ Activity ;   

ELEMENT specifies the "main" entry point for the application. element specifies that this activity should be listed in the system's application Launcher (allowing the user to start the activity).

If you want your application to be self-contained and do not allow other applications to activate its activity, then you do not need any other intent filters.

However, if you want the implicit intent of your activity response to be delivered from other applications, then you must define additional intent filters for your activity. For each type of intent to respond, write a < intent filter, which contains an element and an optional, element and/or < data > element. These elements specify the type of intent that your activity can respond to.

Start Activity
You can launch additional activity by calling Startactvity () to describe the activity that needs to be started in the intent object. Intent specifies the exact activity to start or describe the type of action to perform (and the system chooses the appropriate activity for you, which may be from a different application). An intent can also carry a small amount of data.

When working in your application, you usually need to start a known activity simply. You can use this class name by creating an intent to clearly define the activity you want to start. For example, here's an activity to start another activity called Signinactivity:

new Intent(this, SignInActivity.class);startActivity(intent);

However, your application may also need to perform some actions, such as sending e-mail messages, text messages, or status updates, using data from your activity. In this case, your application might not have its own activity to do so, so you can use the activities provided by other applications to do the work for you. This is where intent really works. You can create an intent to describe an action that you want to perform, and the system will have the appropriate activity from another application. If there are multiple activities that can handle the intent, the user can choose which to use. For example, if you want to allow users to send e-mail messages, you can create the following intent:

Intent intent = new Intent(Intent.ACTION_SEND);intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);startActivity(intent);

Here Extra_email additional intent is the e-mail address. When an e-mail application responds to this intent, it reads the e-mail address in the "to" field. In this case, the activity of the e-mail application begins, and the message is sent to completion, and your activity resumes at the end.

Open an activity with result

Sometimes, you may have an activity with result. In this case, the activity is started by calling Startactivityforresult () (instead of startactivity ()). It then receives result from the subsequent activity, implementing the Onactivityresult () callback method.

For example, perhaps you want users to choose a contact from their phone address book, and your activity can use the information of result to do something. As follows:

Private void pickcontact() {//Create an intent to ' pick ' a contact, as defined by the content provider URIIntent Intent =NewIntent (Intent.action_pick, Contacts.content_uri); Startactivityforresult (Intent, pick_contact_request);}@Overrideprotected void Onactivityresult(intRequestcode,intResultCode, Intent data) {//If The request went well (OK) and the request is Pick_contact_request    if(ResultCode = = Activity.result_ok && Requestcode = = pick_contact_request) {//Perform a query to the contact's content provider for the contact ' s namecursor cursor = getcontentresolver (). Query (Data.getdata (),NewString[] {contacts.display_name},NULL,NULL,NULL);if(Cursor.movetofirst ()) {//True If the cursor is not empty            intColumnIndex = Cursor.getcolumnindex (contacts.display_name); String name = cursor.getstring (columnindex);//Do something with the selected contact ' s name ...}    }}

This example shows that you should use your Onactivityresult () method to handle the result of the activity. The first condition checks whether the request is successful, and if so, returns RESULT_OK

A contentresolver executes a query on the content provider and returns a cursor that allows the data to be read. For more information, see the Content provider documentation.

Destroying Activity
You can turn off activity by using the finish () method. You can also close a standalone actvity by calling the Finishactivity () method.

Note: In most cases, you should not use these methods to complete an activity. As discussed in the following section on the activity life cycle, the Android system manages the activity lifecycle for you, so you don't need to finish () your own activity. Invoking these methods may adversely affect the intended user experience.

manage the life cycle of your activity
Implementing a callback method to manage the life cycle of an activity is critical for developing a robust and flexible application. The life cycle of an activity directly affects its association with other activity, tasks, and backgrounds.

An activity has three states:

Resumed:
The activity is at the top of the screen and has focus. (sometimes referred to as the "running" state.) )
Paused:
is overwritten by another activity, and the other activity is at the top of the screen with focus, but the activity is still visible. That is, another activity that is paused at the top of the activity is still alive (the activity object remains in memory, it maintains all state and member information, and remains connected to the window manager), but can be killed by the system in very low memory situations.
stoped:
Activity is completely obscured by another activity (the current activity is now "background"). The stop activity is still alive (the active object remains in memory, it maintains all state and member information, but does not connect to the window manager). However, it is no longer visible to the user and it can be destroyed by the system.

If the activity is paused or stopped, the system removes it from memory by requiring it to complete (call its finish () method), or simply kills its process. When the activity is opened again (completed or destroyed), it must be created.

Implementing a Lifecycle callback method
When an activity transitions to the different states described above, all callback methods are hooks, and when your activity changes, you can rewrite it to do the proper work. As follows:

 Public  class exampleactivity extends Activity {    @Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);//The activity is being created.}@Override    protected void OnStart() {Super. OnStart ();//The activity is on to become visible.}@Override    protected void Onresume() {Super. Onresume ();//The activity has become visible (it's now "resumed").}@Override    protected void OnPause() {Super. OnPause ();//Another activity is a taking focus (this activity is on to being "paused").}@Override    protected void OnStop() {Super. OnStop ();//The activity is no longer visible (it's now "stopped")}@Override    protected void OnDestroy() {Super. OnDestroy ();//The activity is on to being destroyed.}}

Note: Your implementation of these life cycle methods must call the implementation of the base class before any work is done, as shown in the example above.

These methods define the entire life cycle of the activity. By implementing these methods, you can monitor three scenarios in the life cycle of an activity:
The entire life cycle of an activity occurs OnCreate () to OnDestroy (). Your activity should perform a "global" state (such as defining a layout) in OnCreate (), and OnDestroy () to release all remaining resources. For example, if your activity has a thread running in the background and downloading data from the network, it may create thread oncreate () and then stop Thread OnDestroy ().
The visual life of an activity occurs onstart () to OnStop (). During this time, users can see and interact with activities on the active screen. For example, OnStop () says that it is not visible when a new activity starts. Between the two, you can keep the resources you need to show the activity of that user. For example, you can register a broadcastreceiver in OnStart () to monitor changes that affect your user interface, and unregister it OnStop () when the user cannot see your display. The system can be called OnStart () and OnStop () multiple activities throughout the life cycle process, as the alternation of activity is visible and hidden by the user.
An activity's foreground life occurs Onresume () to OnPause (). During this time, the activity is all other activities on the screen and has the user input focus.

Describes the states that these loops and paths may take for activity. A rectangle represents a callback method that can implement an action when the activity transitions between states.

The lifecycle callback method is listed in the table, describing the life cycle in more detail, and locating each one throughout the life cycle of the actviity. As follows:

Save Activity Status
In the description of the management activity life cycle, it is mentioned that when an activity is paused or stopped, the state of the active is preserved. This is true because the active object is still in memory when all information about its members and current state is paused or stopped. Therefore, any changes made by the user in the activity are preserved so that when the activity returns to the foreground (when it "recovers"), the changes are still there.

However, when the system destroys an activity in order to recover memory, the active object is destroyed, so the system cannot simply restore its state unchanged. Instead, the system must recreate the active object if the user navigates back to it. However, the user does not know about the system destruction activity and re-creates it, so you might want the activity to be exactly the same. In this case, you can ensure that information about important activities is saved by implementing an additional method that allows you to save the status information of your activity: onsaveinstancestate ().

The system calls Onsaveinstancestate () to save the state before the user interrupts the operation. Through this method, you can save the active state information as a name value pair, using methods such as putstring () and Putint (). Then, if the system kills your application process and the user navigates back to your activity, the system re-creates the activity and uses one of these methods to restore the previous state through OnCreate () and Onrestoreinstancestate (). You can extract your saved state and restore the activity status. If there is no state information to recover, then the return parameter will be empty (the argument is empty when the activity is first created).

However, even if you do nothing and do not execute onsaveinstancestate (), some activity states are also restored by the default implementation of the Onsaveinstancestate () activity class. Specifically, the default implementation requires that each view in the layout correspond to the Onsaveinstancestate () method, allowing each view to provide information about itself corresponding to the save. Almost every part of the Android framework implements this method reasonably, so any visible changes to the user interface can be automatically saved, and the state of the activity being recreated can be restored.

Because the default implementation of Onsaveinstancestate () helps to synchronize the state of the UI, overriding these methods saves additional saving state information, and the Onsaveinstancestate () call is implemented before any action is made. Then you rewrite the Onrestoreinstancestate () and you can implement the Restore view state.

Note: onsaveinstancestate () does not guarantee a state recovery under any circumstances, which can only be used to record activity transients and should not be used to store persisted data. The correct approach is to use OnPause () to store persisted data (such as data should be saved to the database) when the user leaves the activity.

There is a good way to test the ability of your application to recover state: Simply rotate the device so that the screen orientation changes. When the orientation of the screen changes, the system destroys and re-creates the activity, which is very important, when your activity is fully restored, it is reproduced because the user often rotates the screen while using the app.

handling changes to configuration
Some device configurations can be changed at run time (such as screen orientation, soft keyboard). When such a change occurs, Android re-runs the activity (the system calls OnDestroy () and then immediately calls OnCreate ()). The purpose of this behavior is to help your application automatically load with alternative resources, adapting to device changes,
If you properly design your activity to handle a reboot, your application will be more flexible in handling this situation when the screen orientation changes.
The best solution is to save and restore your activity using onsaveinstancestate (), Onrestoreinstancestate () (or OnCreate ()), as mentioned above.

Coordination activities

When one activity starts to another activity, the process is the transition of the life cycle state. The first activity is destroyed and paused (it is not destroyed, still a visible background), it is important to understand that the first activities are not completely stopped. In contrast, the process of initiating a second activity is the first activity overlap.

The above is a simple translation of the activity section of the official Android document, do not spray ~

"Android Official document" translation Android Official document-activities (i)

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.