Activity of four Android Components

Source: Internet
Author: User

  Activity Definition

Activity is an application component that provides a screen and allows users to interact with each other, such as dialing, taking photos, sending emails or browsing maps, every activity is given a window used to draw a user interface. Generally, the window is full of screens, but it may be a little smaller than the screen and float on other windows.

An application is usually composed of multiple closely related activies. A typical activity is specified as a "Main" activity in the application. The first time a user runs the application, the activity is displayed. To execute different behaviors, each activity can run another activity. Each time a new activity is enabled, the previous activity is stopped, and the system keeps the activity in the stack (rollback stack). When a new activity runs, it is pushed to the top of the stack and gives users focus. Stack rollback follows the stack mechanism of "back-in, first-out". Therefore, when a user presses the return button on the current activity, it pops up (destroyed) from the top of the stack) and the previous activity is restored to the current one.

  

  Two important callback Methods

Oncreate ()

You must implement this method when creating your activity. In this implementation body, you should initialize the necessary components. Here you also call setcontentview () to define the layout of your interface.

Onpause ()

The system calls this method to demonstrate that the user has left your activity (although it cannot always be understood that the activity has been destroyed ), here, you usually need to submit any changes to retain the Session of the current user (because the user may not return again ).

  

  Declare activity in manifest

You must declare your activity in manifest to associate your system, open your manifest file, and add an <activity> element as a child element of the <Application> element. For example:

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

You can also include several other attributes in the acitivity element. For details, refer<activity>

  

  Run an activity

You can callStartactivity () to run another activity and passIntent to describe the activity you want to run.

In your application, you often run a known activity. You can create another intent to accurately define the activity you want to run. For example:

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

However, your application may also want to execute some actions, such as sending an email, text information, or status update. In this case, your application may not have its own activities to execute such actions. Therefore, you can run the activities provided by other applications in some ways, which is the true value of intent. For example, if you want to send an email, you can create the following intent.

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

  

  Run an activity with returned results

Sometimes, you want to get results from the activity you are running. In this caseStartactivityforresult () to run the activity (instead of startactivity ()). Obtain results from subsequent activities.Onactivityresult () callback method. When the subsequent activity completes the operation, it returns a result to yourOnactivityresult () method.

View code

private void pickContact() {    // Create an intent to "pick" a contact, as defined by the content provider URI    Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);    startActivityForResult(intent, PICK_CONTACT_REQUEST);}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {    // If the request went well (OK) and the request was 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 name        Cursor cursor = getContentResolver().query(data.getData(),        new String[] {Contacts.DISPLAY_NAME}, null, null, null);        if (cursor.moveToFirst()) { // True if the cursor is not empty            int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);            String name = cursor.getString(columnIndex);            // Do something with the selected contact's name...        }    }}

This instance shows that you shouldOnactivityresult. The first case checks that if the request is successfulResultcode will beResult_ OK. Here, the Code queries the data returned by the activity in intent.

 

  Close an activity

  You can call the finish () method to close an activity. You can also call the finishactivity () method to close an independent activity that you have previously run.

  

  Manage activity Lifecycle

  An activity has three necessary states:

  Resumed

    The activity is at the front of the screen and obtains the focus.

  Paused

The other activity is in the foreground and obtains the focus, but the previous activity is still visible. That is, another activity is on top of an activity, and the activity is partially transparent or does not completely cover the entire screen. A paused activity is completely alive (the activity object is kept in the memory, maintains all the status and member information, and is attached to window management). However, it can be killed by the system when the memory is very low.

  Stopped

The activity is completely overwritten by another activity (the activity is in the background "). A stopped activity is also alive (the activity object is kept in the memory and maintains all status and member information, but is not attached to window management). However, it is no longer visible to users and will be killed when the system requires memory.

If an activity is paused or stopped, the system can destroy the memory through finish (callOr kill the process. When the activity is opened again (after finished and killed), it must be completely created.

  

  Lifecycle callback Method

View code

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 about to become visible.    }    @Override    protected void onResume() {        super.onResume();        // The activity has become visible (it is now "resumed").    }    @Override    protected void onPause() {        super.onPause();        // Another activity is taking focus (this activity is about to be "paused").    }    @Override    protected void onStop() {        super.onStop();        // The activity is no longer visible (it is now "stopped")    }    @Override    protected void onDestroy() {        super.onDestroy();        // The activity is about to be destroyed.    }}
  • The entire lifecycle of an activity is called.Oncreate () andBetween ondestroy (), your activity should execute setup of "global" State (such as defining layout) in oncreate, release all reserved resources on ondestroy ().
  • The visible life cycle of an activity occurs in the callOnstart () andOnstop (). In this process, you can see the activity on the interface and operate on it. Between the two methods, you can retain the resources that need to be presented to the user in the activity. For example, you can registerBroadcastreceiverOnstart () to listen for changes that affect your UI, and inIn onstop (), log off when the user no longer sees what you display. The system may call multiple times throughout the lifecycle.Onstart () andOnstop () method, when the activity is visible and hidden, the two States Alternate.
  • The foreground life cycle of an activity is called.Onresume () andBetween onpause (), in this process, the activity is in front of all other activities on the screen and there is a user input focus. Because this status can be passed frequently, the code in the two methods should be as lightweight as possible to avoid waiting for users.

Shows the lifecycle of the entire activity.

  

Method Description Killable after? Next
onCreate()

Called when the activity is created for the first time. This is generally used for configuration-create a view, bind data to the List, and so on. This method is passed to a bundle object, which contains the status of the last activity, if the status is captured (view saving activity state ). Next, onstart () is always called ().

No onStart()
onRestart()

The activity is called after it has been stopped and is run again. Next, onstart () is always called ().

No onStart()
onStart()

Called before activity is visible to users. Next, we will call onresume () if the activity is in the foreground or the onstop () acitume is hidden.

 

No onResume() 
Or
onStop()
onResume()

Activity is called before it can interact with users. At this point, the activity is at the top of the activity stack. You can enter it. Next, we will always callonPause()。

No onPause()
onPause()

It is called when the system is starting to restore another activity. In this method, users usually submit unsaved changes to keep the data persistent and stop the animation and other tasks that may consume CPU. Whatever the processing, it should be very fast, because the next activity will be restored until it returns.

Next, call onresume () if the activity is returned to the front, or onstop () if it is invisible to the user.

Yes onResume() 
Or
onStop()
onStop()

Called when the activity is no longer visible to the user. It may occur because it is destroyed, or because another activity (whether existing or new) has been restored and overwritten.

Next, callOnrestart () if the activity returns to interact with the user, or callsOndestroy () If activity is destroyed.

Yes onRestart()
Or
onDestroy()
onDestroy()

Called before the activity is destroyed. This is the last call that the activity will receive. It can be called either because the activity ends (finish () is called ()), or the system temporarily destroys the activity instance to release the space. You can useIsfinishing () to distinguish the two scenarios.

Yes Nothing

Not Guaranteed hereOnsaveinstancestate () will be called before your activity is destroyed, because there is a situation where there is no need to save the status (for example, the user uses the rollback key to exit your activity, because the user explicitly wants to close the activity ). If the system calls onsaveinstancestate (), it willBefore onstop () and possibly beforeBefore onpause.

Because onsaveinstancestate () is not guaranteed to be called, you should use it to save the status (ui status) passed between activities-you should never use it to save persistent data, instead, you should use onpause () to save persistent data (such as saving data to the database) when the user leaves the activity.

  

  Processing configuration (Configuration) Change

Some device configurations can be changed at runtime (such as screen orientation, keyboard availability, and language ). When such a change occurs, Android re-creates a running activity (System CallOndestroy (), and then immediately call oncreate ()). This designed behavior can help your application automatically load to your application through the optional resources you provide to adapt the program to new configurations (for example, different la s for different screen direction and size ). For more information, see handling runtime changes.

 

It is just for you to understand it. If you cannot clearly express it, please point it out.

Original article: http://developer.android.com/guide/topics/fundamentals/activities.html

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.