Four Android components-Activity details

Source: Internet
Author: User

The main content of this article includes 1. activity creation, configuration, and use; 2. activity jump and transfer value; 3. startActivityForResult; 4. activity lifecycle.

1. Create, configure, and use an activity

Activity is an application component that provides users with a visual interface for convenient operations, such as calling, taking photos, sending emails or browsing maps. Each activity provides a visual window, which overwrites the entire screen, however, in some cases, some smaller windows may float on another window.

Creating an Activity in android is simple. Compile a Java class inherited from android. app. Activity and declare it in AndroidManifest. xml. The following is an Activity instance to study the lifecycle of an Activity:

public class Example extends Activity {      private static final String LOG_TAG = EX01.class.getSimpleName();      @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.main);          Log.e(LOG_TAG, "onCreate");      }      @Override      protected void onStart() {          Log.e(LOG_TAG, "onStart");          super.onStart();      }      @Override      protected void onResume() {          Log.e(LOG_TAG, "onResume");          super.onResume();      }      @Override      protected void onPause() {          Log.e(LOG_TAG, "onPause");          super.onPause();      }      @Override      protected void onStop() {          Log.e(LOG_TAG, "onStop");          super.onStop();      }      @Override      protected void onDestroy() {          Log.e(LOG_TAG, "onDestroy ");          super.onDestroy();      }  }  

PS1:

The two most important methods are:
OnCreate () -- this is a required function for initialization. Remember: you must call the setContentView () function in this function to set the Activity interface.
OnPause () -- this is important, but it is not required. This function is called when the user leaves the Activity (this generally does not mean that the Activity will be destroyed ). In this function, you generally need to submit the data that needs to be saved (because the user may not return to this Activity)

Android applications require all application components (Activity, Service, ContentProvider, BroadcastReceiver) to be explicitly configured. You only need to add child elements to the elements to configure the Activity.
For example, AndroidManifest. xml (a list file is similar to a Web. xml file in a web application)
In AndroidManifest. xml, the Activity is described by the node. After the apk file is installed, the system searches for the Activity based on the instructions here. The instructions in this example are as follows:

        
                         
          
      

PS2:
The content in this label is described as follows:
Name: Specifies the implementation class of the Activity.
Icon: icon corresponding to the Activity
Label: label of the Activity.
In addition, when configuring an Activity, you usually need to specify one or more Specifies the Intent that the Activity can respond.
Note that there is a "." at the beginning of the activity name value. If you forget it, the program runs incorrectly, and it is difficult to find out the cause of the error.

Secondly, whether you are using Activity only internally or externally, you must go to AndroidManifest. register in the xml list file. Otherwise, an inexplicable error will still occur, but you do not need to add an intent filter for acitivity during internal use.

Where,
Is the filter. It indicates that this Acitivity is the main entry of the program, It indicates that this Acitivity must be listed in the Application List of the system.
If the Activity in the program you write does not need to be called by other programs, you do not need to add any intent filter for the Activity. However, the program must have an Activity specified as "main" Action and "launcher" category. The Activity in your own process can be called in a more direct way.

However, if you want your Activity to be called by other programs, you need to add an intent filter for it. These intention filters include, And . These elements indicate the type of intent that your activity responds. The intent filter is not described here.

2. jump between activities and pass values

We have learned how to start an Activity. When starting another Activity, an Activity may need to pass values. Value passing between activities is implemented through Bundle.

1) Introduction to Activity redirection

The most common and common page Jump code is as follows:

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


Of course, OtherActivity also needs to be defined in AndroidManifest. xml.

2) Bundle value transfer

1. If there is a small amount of data, for example, if you only need to pass a Name, you only need to add "intent. putExtra (" Name "," feng88724 ");". The Code is as follows:

Intent intent = new Intent();intent.setClass(A.this, B.class);intent.putExtra("Name", "feng88724");startActivity(intent);

2. If the data volume is large, you need to use the Bundle class. The Code is as follows:

If we want to say something to the "recipient" Activity, we can pass our message through the "e-mail" below:

Intent intent = new Intent (CurrentActivity. this, OtherActivity. class); // create an email Bundle bundle with the "recipient address" = new Bundle (); // create an email content bundle. putBoolean ("boolean_key", true); // write content bundle. putString ("string_key", "string_value"); intent. putExtra ("key", bundle); // encapsulate email startActivity (intent); // start a new Activity

So how should we receive the "recipient? Use the following code in onCreate () of the OtherActivity class or any other place to open this "e-mail" and read the information:

Intent intent = getIntent (); // receive email Bundle bundle = intent. getBundleExtra ("key"); // open the email bundle. getBoolean ("boolean_key"); // read content bundle. getString ("string_key ");


3. Usage of startActivityForResult

Sometimes, after a page Jump, you need to return to the previous page and retain the user's previous information. What should you do at this time?

After the page jumps, the previous Activity has been destroy. To return and display data, You must wake up the previous Activity and call a method to obtain and display data.

To achieve this effect, perform the following steps:

1. When you jump from page A to page B, you cannot use the "startActivity ()" method, but the "startActivityForResult" method.

2. In the Activity on page A, you must override the onActivityResult method.

OnActivityResult (int requestCode, int resultCode, Intent data)

The first parameter: This integer requestCode is provided to onActivityResult to confirm from which Activity the returned data is returned. This requestCode corresponds to requestCode in startActivityForResult.
The second parameter: This integer resultCode is returned by the Child Activity through its setResult () method.

The third parameter is an Intent object with the returned data.

For example:

Import android. app. activity; import android. content. intent; import android. OS. bundle; import android. util. log; import android. view. view; import android. widget. button; public class MainActivity extends Activity {private final static String TAG = "MainActivity"; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); Button btnOpen = (Button) this. findViewById (R. id. btnOpen); btnOpen. setOnClickListener (new View. onClickListener () {public void onClick (View v) {// get the data returned after the Activity is closed. // The second parameter is the request code, you can enter startActivityForResult (new Intent (MainActivity. this, OtherActivity. class), 1) ;}}) ;}/ *** to obtain the returned data, the onActivityResult method must be rewritten in the previous Activity (MainActivity class) ** requestCode request code, that is, call startActivityForResult () to pass the previous value * resultCode result code. The result code is used to identify the new Activity from which the returned data comes */@ Override protected void onActivityResult (int requestCode, int resultCode, intent data) {String result = data. getExtras (). getString ("result"); // get the data Log returned after the new Activity is disabled. I (TAG, result );}}

When the new Activity is disabled, the data returned by the new Activity is transmitted through Intent. The android platform calls the onActivityResult () method of the previous Activity, input the Intent that stores the returned data as the third input parameter, and use the third input parameter in the onActivityResult () method to retrieve the data returned by the new Activity.

Use the startActivityForResult (Intent intent, int requestCode) method to open a new Activity. Before closing a new Activity, you must use the setResult (int resultCode, Intent data) provided by the system to return data to the previous Activity) method implementation:

Import android. app. activity; import android. content. intent; import android. OS. bundle; import android. view. view; import android. widget. button; public class OtherActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. other); Button btnClose = (Button) findViewById (R. id. btnClose); btnClose. setOnClickListener (new View. onClickListener () {public void onClick (View v) {// The data is returned using Intent intent = new Intent (); // Save the returned data to Intent intent. putExtra ("result", "My name is ting"); // you can specify OtherActivity to return data. this. setResult (RESULT_ OK, intent); // close Activity OtherActivity. this. finish ();}});}}


The first parameter value of the setResult () method can be defined according to business needs. The RESULT_ OK used in the code above is a constant defined by the system Activity class. The value is-1, the code snippet is as follows:

public class android.app.Activity extends ......{  public static final int RESULT_CANCELED = 0;  public static final int RESULT_OK = -1;  public static final int RESULT_FIRST_USER = 1;}

PS3:

The role of the Request Code:

Use the startActivityForResult (Intent intent, int requestCode) method to open a new Activity. We need to input a Request Code (the second parameter) for the startActivityForResult () method ). The value of the Request Code is set by the user according to the business needs, used to identify the request source. For example, a single Activity has two buttons. Clicking these two buttons will open the same Activity. No matter which button opens the new Activity, when the new Activity is closed, the system will call the onActivityResult (int requestCode, int resultCode, Intent data) method of the previous Activity. In the onActivityResult () method, if you need to know that the new Activity is opened by that button, and make corresponding business processing :.


4. activity Lifecycle

1. Concept of a task:

A task is actually the stack of an activity. It is composed of one or more activities to complete a complete user experience. In other words, a task is an "application" (either one or multiple, for example, suppose that you want users to see a street map somewhere. If an activity with this function already exists, you need to put the request information in an Intent object and pass it to startActivity (). The map browser displays the map. When you press the BACK key, your activity will be displayed on the screen again. At this time, the task is composed of two related activities in the application) the bottom of the stack is the Activity that starts the entire task. The top of the stack is the Activity that the currently running user can interact with. When another activity starts, the new activity is pushed to the stack, and become the currently running activity. The previous activity remains in the stack. When you press the BACK key, the current activity goes out of the stack, and the previous activity is restored to the currently running one. Objects are actually stored in the stack. The Activity in the stack will never be rearranged and only be pushed in or out. Therefore, if multiple map browsers are required, in this case, multiple instances of the same Activity subclass exist simultaneously in a task.

2. All activities in the task are moved as a whole. The entire task (that is, the activity stack) can be moved to the foreground or to the background. For example, the current task has four activities in the stack -- three under the current activity. When you press the HOME key, you return to the Application Loader and select a new application (that is, a new task ). The current task is merged into the background, and the root activity of the new task is displayed. Then, after a while, the user returned to the Application Loader again and selected the previous application (the previous Task ). So the task, with all the four activities on its stack, once again arrived at the front-end. When the user presses the BACK key, the screen does not show the activity that the user just left (the root activity of the previous Task ). Instead, the top activity in the current task stack is popped up, and the previous activity in the same task is displayed.

3. The Android system is a Multi-Task operating system. You can use your mobile phone to listen to music and execute multiple other programs. Every time you execute an application, it will consume more system memory. when too many programs are executed at the same time, or the closed program does not properly release the memory, the system will feel slower and slower, even unstable.

To solve this problem, Android introduces a new mechanism-Life Cycle ).

The lifecycle of an Android application is managed by the Android framework, rather than directly controlled by the application. Generally, every application (the entry is generally an onCreate method of an Activity) will generate a Process ). When the system memory is about to be insufficient, the process will be automatically reclaimed according to the priority. No matter the user or developer, it cannot be determined when the application will be recycled. Therefore, to prevent data loss and other problems, it is important to understand the lifecycle.

Four States and seven important methods of an Activity throughout its lifecycle

1) Four statuses

1. Active/Running status
When the Activity runs on the front-end of the screen (at the top of the current task Activity stack), it obtains the focus to respond to user operations, which is in the running status, at the same time, only one Activity is Active or running.

(Running) Status

1. Paused status
When the Activity loses focus but is still visible to the user (for example, if there is another transparent Activity on it or a pop-up window such as Toast and AlertDialog), it is paused. The paused Activity is still alive (it retains all the status and member information and maintains the connection with the window manager), but can be killed by the system when the system memory is very small.

3. Stop status

When it is completely blocked by another Activity, it is in the stopped state and retains all the status and member information. It is invisible to users. When memory is needed elsewhere, it is often killed by the system.

4. Dead status

The Activity has not been started, has been manually terminated, or is not active when it has been recycled by the system. To manually terminate the Activity, you can call the "finish" method in the program.

If it is recycled by the system based on the collection rules when the memory is insufficient, it may be because the memory is insufficient.

When the memory is insufficient, the Dalvak virtual opportunity recycles the memory according to its memory reclaim rules:

1. Reclaim processes unrelated to other activities or Service/Intent referers first (that is, reclaim standbys first ).

Therefore, it is recommended that some background operations be performed as services.

2. Invisible (Stopped) Activity

3. Service Process (unless there is no memory available, it will be destroyed)

4. inactive visible (Paused status) Activity

5. Currently Running (Active/Running) Activity

2) 7 important methods

When an Activity enters another State from one state, the system automatically calls the following

To notify users of such changes

The system will call the first time an Activity is instantiated,

This method is called only once throughout the lifecycle.

Usually used for initialization settings: 1. Set the layout file to be used for the Activity; 2. Bind a listener to the button and perform other static settings.

OnCreate (Bundle savedInstanceState );

When the Activity is visible, the system calls

OnStart ();

When the Activity is stopped and restarted, the system calls

OnRestart ();

When the Activity is visible and the user focus is available for interaction, the system calls

OnResume ();

When the system starts another Activity, it is called by the system to save the persistent data in the existing Activity and stop the animation before the new Activity starts. This implementation method must be very fast. After the activity is disabled, the system does not recycle the memory. The user will expect that when he returns to this activity again, it will remain like the last time he left. At this time, onSaveInstanceState () is used. The onSaveInstanceState () method is used to save the status before the Activity is killed and is triggered before onPause, this method needs to be rewritten when the system destroys the Activity to save memory (the user does not want to destroy the Activity). When the Activity is instantiated again, it will pass onCreate (Bundle savedInstanceState) pass stored temporary status data into the system because the onSaveInstanceState () method is not always called. The trigger condition is (press the HOME Key, press the power button to close the screen, and switch between the screen ), you should only override onSaveInstanceState () to record the temporary status of the activity, rather than persistent data. OnPause () should be used to store persistent data.

OnPause ();

Called by the system when the Activity is completely overwritten and invisible by the new Activity

OnStop ();

When the Activity (the user calls finish () or the system is killed due to insufficient memory) is destroyed by the system, the system calls the Activity (the entire life cycle is only called once) to release onCreate () resources created in the method, such as the end thread

OnDestroy ();

PS4:

1. When the android: configChanges of the Activity is not set, the life cycle of the screen is re-called, the screen is executed once, and the screen is split twice.

2. When setting the Activity's android: configChanges = "orientation", the screen will be switched to call each lifecycle, and the screen will be executed only once

3. When the android: configChanges = "orientation | keyboardHidden" of the Activity is set, the live cycle is not re-called and only the onConfigurationChanged method is executed.

4. When Toast and AlertDialog are displayed in the event generated by the current Activity, the lifecycle of the Activity will not change.

When the Activity is running, press the HOME Key (which is the same as if it is completely overwritten): onSaveInstanceState --> onPause --> onStop. When the Activity enters the activation status again: onRestart --> onStart ---> onResume

Finally, let's talk about the similarities and differences between the Activity and Servlet:

1. Web developers should be familiar with Servlet concepts. In fact, Activity is a bit similar to Servlet for Android applications. A Web application usually requires multiple servlets. Similarly, an Android Application usually requires multiple activities. For Web applications, Servlet is mainly responsible for interacting with users and presenting the application status to users. For Android applications, Activity has similar functions.

2. Similarities (in part): developers do not need to create their instances or call their methods. These are called by the system in callback mode, their lifecycle is managed externally. They cannot call each other so far, so they cannot exchange data directly.

3. Differences: one is the B/S mode and the other is the C/S mode. The Activity uses components to build the interface, servlet generates text responses mainly from IO to the viewer.

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.