Android Official Docs app components (activities)

Source: Internet
Author: User
Tags call back

Activity is the top four components of Android, this article will introduce the meaning of activity, create, start, destroy, life cycle and so on.

To access the official text, you can click on this link: "Activities"


Activity is a class that is the carrier of the Android rendering interface for interacting with user actions, such as dialing, photographing, sending mail, displaying maps, and so on. Each activity carries a window, which is used to draw the UI (User Interface). In general, the window fills the entire screen (fill), and sometimes it can hover over other windows (float on top of another window).

Typically, an Android application can contain multiple activity, with each activity being loosely coupled (loosely bound to every other). Typically there is a primary activity that starts when the program is started, and each activity can initiate other activity, and whenever a new activity is started, the original activity is in the stop state, And the activity instance is saved in the back stack, and the newly initiated activity is loaded into the back stack and gets the focus. The storage mechanism of the back stack is LIFO (last in, first out), so when the user taps the Back button, the top activity pops up from the top of the stack and is destroyed, and the activity in the stop state enters the resume state. For an official document on the task stack and return stack, you can refer to the official documentation: tasks and back stack, which I will translate later.

When a new activity starts, the original activity will be in the stop state, in which the activity will callback its corresponding life cycle method to change state, activity has several life cycle callback methods, in each method, can do some corresponding work , such as when the activity enters the stop state, the system will callback the OnStop () method, in which you can release some large objects (release any large objects), such as network or database connection, when the activity enters the resume state , the system will callback the Onresume () method, in which you can regain some important resources (eacquire the necessary resource) and restart some of the terminated actions (the resume action that were Interrupted) and so on.

Create activity (Creating an activity)

In order to create an activity, you must inherit the activity class and override the life cycle method. such as OnCreate (), OnStop (), Onresume (), OnDestroy (), etc. The most important callback methods are:

    • OnCreate (): The method must be overridden and the system will callback when the activity is created. In this method, you can do some of the necessary component initialization, and you must call the setContentView() method binding view.

    • OnPause (): When activity is visible to invisible State, the system will callback the method. In this method, the user's change operation should be persisted.

For more information on the official text of the activity lifecycle, you can click on this link: "Managing the Activity Lifecycle".

Binding UI (Implementing a user interface)

The activity-hosted UI consists of a series of nested views (a hierarchy of view) that inherit from the view class, each of which controls a rectangular area and interacts with the user.

Android contains a large number of view, you can customize the layout of the view, such as button, Text field, checkbox, or just an image. The ViewGroup class also inherits from the view class, which is responsible for the layout of the view, linear layout, a grid layout, and relative layout are different layouts. You can also inherit the view or ViewGroup to customize your layout.

The most common way to define layout is to create an XML layout file in a resource folder. In this way, you can reduce the coupling between the layout and the activity implementation logic, which you can use to setContentView() bind an activity to a layout.
For more information about the layout, you can refer to the official document "User Interface".

Registering activity in the manifest file (declaring the activity in the manifest)

In order for the system to recognize the activity defined in the code, you need to register the activity in the manifest manifest file in the following format:

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

In the Activity tab, only android:name attributes are not default. Use theme, icon, and other properties to set themes, icons, and so on for your activity. Once you have identified the activity name, you can no longer modify it, or it will break some of the features, for this aspect, you may refer to this blog: "Things that cannot changes"

Use Intent-filters (using intent filters) in the Activity tab

In the Activity tab, you can specify multiple <intent-filter> tags that define the nature of the activity and how other applications start the activity.

To define an activity as the main entry for an application, you can define it 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 ;   

Do not set intent-filter for this activity if you want activity to be started only by your own application (not let other applications to activate its activities). Only one activity Intent-filter in an application is the "main" action and the "launcher" category. Android does not encourage the use of explicit intent to initiate cross-app activity.

For more information about Intent-filter, you can refer to the official documentation: "Intents and Intent Filters", or my translated blog: "Android official Docs app components (Intents and Intent Filters) ".

Start activity (starting an activity)

In order to start an activity, you can call the startActivity() method and pass in the intent object parameter. The intent object can contain the action parameter, which specifies the nature of the target activity, and intent can carry a small amount of data.
If you start the activity of the same application, you can use the display intent, such as:

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

More often, an activity is initiated through an implicit intent, such as initiating an activity that sends a message:

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

The system provides a number of built-in actions to implicitly initiate the activity of the system's own application, and for this part you can refer to the official text: "Common Intents" or my translator's blog: "Android Official document app Components (Common Intents).

Start activity and return results (starting an activity for a result)

In order to get the result of initiating activity, you can call the Startactivityforresult () method instead of the StartActivity () method, and the Onactivityresult () The callback method receives the result (obtained from the intent parameter of the method).
Here's an example of getting an address book contact:

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 ...}    }}
Terminate activity (shutting down an activity)

Call the Finish () method to terminate the activity manually, or you can call the Finishactivity () method to manually terminate the activity that was started before the foreground.

! Please note: In most cases, do not manually terminate activity,activity will automatically terminate based on the state of its life cycle. Manually terminating the activity can affect the user experience, except in some extreme cases, do not manually terminate the activity.

Manage the life cycle of your activity (managing the Activity Lifecycle)

The lifecycle of activity can be managed through the activity life cycle method of the callback. The activity will be at least three of these states:

    • Resumed (or running): The activity is in the foreground and gets the focus.

    • Paused: When another activity is in the foreground and has the focus, the original activity loses focus but is still partially visible, when the active activity is in pause state. The activity in the pause state still has its instance in memory and is attached to Window manager, which has all the states before the pause, but the system can destroy it in memory and its low (can be killed by the systems in extremely Low memory situations).

    • Stopped: When another activity completely obscures the original activity (completely obscured by another activity), the original activity is in Stopped state. Activity in the stopped state still has its instance in memory, but it is no longer attached to Window manager, and the system can destroy it when it needs memory (can be killed by the system time memory is needed else where).

When activity is in a pause or stopped state, the system can call the finish () method to destroy the activity instance when its memory is tight, or simply kill the application's process (simply killing its processes). When you need to start the activity again, the instance must be recreated.

Override Lifecycle callback method (implementing the Lifecycle callbacks)

When activity switches between the different states described above, the system will call back to the corresponding method in the activity 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: Before overriding these callback methods, be sure to call their parent class methods first. Just like in the example.

Within these callback methods, three nested inner loop lifecycles (three nested Loops) are included:

    • Full life cycle (entire lifetime): from OnCreate () to OnDestroy (). You should handle some global content in two methods, such as initializing the layout resource in OnCreate () and releasing it in the OnDestroy () method. If you need to open a thread in the activity to access the network download file, you should create the thread in OnCreate () and stop the thread in OnDestroy ().

    • Visible life cycle (visible lifetime): From OnStart () to OnStop (), the user can see and interact with the UI interface that the activity hosts in this lifecycle (the user can sees the activity On-Screen and interact with it), such as when the OnStop () method is called back, the activity is no longer visible, and the new activity is in the startup state. Between these two methods, you can show the user some resources, such as you can register Broadcastreceiver in the OnStart () method and de-enroll in the OnStop () method.

    • Foreground life cycle (foreground lifetime): from Onresume () to OnPause (), during which the activity is at the top of all other activity and gets the user input focus, the system can switch quickly in the foreground life cycle, OnPause () is called back when the device is hibernating or the dialog box pops up. Just because you can switch quickly, try not to do heavier work in either of these methods.

Demonstrate the entire process of the activity life cycle:

The following table summarizes the activity life cycle:

Method Description can the system kill activity after the method is executed? the next callback method
OnCreate () When the activity is first started, the callback can do static initialization for the activity, such as initializing view, binding data to the ListView, and so on; The method callbacks a bundle parameter that holds the information stored in the activity last time. Whether OnStart ()
Onrestart () When the activity is in the stop state and ready to start from the new Whether OnStart ()
OnStart () When activity is visible, the activity instance is just pressed into the back stack Whether Onresume () or onStop ()
Onresume () Callback before the user is in an interactive state Whether OnPause ()
OnPause () Called before other activity is ready to start, it is common to persist some data in this method, stop the animation, and so on. The action performed in this method cannot be too cumbersome, or it will affect the creation of the new activity. Is Onresume () or onStop ()
OnStop () Callback when UI interface is no longer visible Is Onrestart () or OnDestroy ()
OnDestroy () Called when the activity sample is destroyed. It may be that the developer has invoked the finish () method to the OnDestroy () callback, or the system's memory is tense and callback, and you can call the Isfinishing () method to determine if the OnDestroy () callback is the one described above. Is No

In the Can the system kill activity after the method is executed? "In this column, there are three methods that result in" Yes "(OnPause (), OnStop (), and OnDestroy ()). When content and its tense, the OnPause () method is called back, and the OnStop () and OnDestroy () methods are not called back, so some key, lightweight data should be persisted in the OnPause () method, and in the other callback methods that are "no" This is not to say that activity cannot be killed during this time, except that the situation is basically nonexistent (no space available in memory).

Save activity status (saving activity State)

When the system callbacks the OnPause () or OnStop () method, the activity instance is still visible in memory, so when activity is re-visible, the data in the activity is still displayed intact.
However, sometimes the activity instance is recycled because the system is out of memory, and when the activity is re-created, the system will not be able to guarantee that the data entered in the interface can be completely restored, and the Onsaveinstancestate () method needs to be rewritten to save the data.
The Onsaveinstancestate () method is typically called back when the activity instance is about to be reclaimed by the system (the activity vulnerable to destruction). You can save data in the form of key-value pairs in the bundle parameters returned by the method, and the bundle parameter is passed to OnCreate () and Onrestoreinstancestate () when the activity is destroyed due to memory tension, screen turn-screen, etc. method, when the activity is started again, the callback OnCreate () or onrestoreinstancestate () can be retrieved from the bundle parameter from the previously saved data. If there is no data in the bundle, it will be null.
The difference between onCreate () and Onrestoreinstancestate () is that the former must be called back each time the activity is initialized, so the bundle parameter of the postback may be null, which requires a judgment before the bundle parameter is fetched. And the latter will only call back after the data has been saved to the bundle, so there is no need to judge whether the bundle is empty, and the bundle can be obtained directly.

The activity's data is saved as follows:

The Onsaveinstancestate () method is not necessarily called before destroy, and Onsaveinstancestate () may be onstop () or even onpause () when the user clicks the Back button to exit the activity actively. have been called back before.

Even if you do not actively replicate the Onsaveinstancestate () method, the system will also call back the method and save some layout information (such as checkbox check, EditText type), when the device is switched from vertical to horizontal screen The layout of the horizontal screen will be loaded, and the information saved in Onsaveinstancestate () is restored, and the entire save process is restored by the same ID of the different layouts of the same view, that is, if you need to save the type information for a control, You only need to specify the same ID for the control when you set a different layout for it, such as two layouts for the screen.
Of course, you can also set the Android:saveenabled property to False in the Activity tab, or call setsaveenabled (false) to prevent onsaveinstancestate () Method automatically saves layout information, but is generally not recommended.

In real-world development, it is recommended to rewrite the Onsaveinstancestate () method to hold additional important information and call the parent class's Onsaveinstancestate () method before saving the information, so that information such as layout layouts, controls, and so on can be saved.

! Please note: since the Onsaveinstancestate () method is not guaranteed to be called back, it is common to use the Onsaveinstancestate () method to save the instant information on some UI interfaces without applying it to save persisted content; OnPause () method to save data that needs to be persisted (such as storing data in database)

You can test whether the information is saved effectively by rotating the screen, because the rotation of the screen occurs frequently during the use of the device, and if the data is not stored well, the user experience is compromised, and the screen rotation is a process of destroying and rebuilding the activity, which is a good test.

Handling problems with configuration changes (handling configuration changes)

The configuration of the device may change at run time (such as rotating the screen, the keyboard is visible, the language environment changes, etc.), at which point the OnDestroy () method is called back, and then immediately callback the OnCreate () method, the information previously saved on the interface may disappear.
The best solution is to callback the Onsaveinstancestate () and Onrestoreinstancestate () methods (or OnCreate ()). For more information on configuration changes, you can refer to this official document "Handling Runtime changes"

Coordinating startup activity (coordinating activities)

When activity A starts activity B, the following callbacks will occur:

    1. Activity a callback OnPause ();
    2. Activity b Callback OnCreate (), OnStart (), and Onresume (); (activity B is at the foreground)
    3. Activity a callback OnStop (); (activity A is no longer visible)

One scenario for the above step is that if you want to save the data in activity A to database and get it in activity B, you should save it in the OnPause () method in activity A, not in the OnStop () method.

Android Official Docs app components (activities)

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: 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.