Android activity components

Source: Internet
Author: User
Activity Lifecycle

Like the MIDlet of j2m's, in Android, the lifecycle of the activity is handed over to the system for unified management. Unlike MIDlet, all the activities installed on Android are equal.

Activity Status and transition between States

In Android, activity has four basic states:

  1. Active/runingAfter a new activity is started into the stack, it is at the front end of the screen and at the top of the stack. At this time, it is visible and can interact with users.
  2. PausedThe status when the activity is overwritten by another transparent or dialog style activity. At this time, it is still connected to the window manager, and the system continues to maintain its internal status, so it is still visible, but it has lost its focus, so it cannot interact with users.
  3. StopedWhen the activity is overwritten by another activity and the focus is not visible
    Stoped
    Status.
  4. KilledWhen the activity is killed or recycled by the system or is not startedKilledStatus.

When an activity instance is created, destroyed, or started, it is converted between the four States. This conversion relies on the action of the user program. The time and conditions for activity switching between different States are described:

Figure 1. Activity Status transition

As shown above, the android programmer can determine the "life" of an activity, but cannot determine its "death". That is to say, the programmer can start an activity, however, you cannot manually "end" an activity. When you callActivity. Finish ()Method, the result is the same as pressing the back key: Tell activity manager that the activity instance has completed the corresponding work and can be "recycled ". Then the activity Manager activates the activity on the second layer of the stack and re-enters the stack. At the same time, the original activity
Pushed to the second layer of the stack, from active to paused. For example, if activity2 is started from activity1, activity2 is currently at the top of the stack, and activity1 is the second layer. When we callActivity2.finish ()Method, activity manager re-activates activity1 to merge into the stack, and activity2 changes from active to stoped,Activity1. onactivityresult (INT requestcode, int
Resultcode, intent data)
The method is executed, and the data returned by activity2 isDataThe parameter is returned to activity1.

Activity Stack

Android manages an activity through an activity stack. The status of an activity Instance determines its position in the stack. The front-end activity is always at the top of the stack. When the current activity is destroyed due to exceptions or other reasons, the activity on the second layer of the stack will be activated and go up to the top of the stack. When a new activity is started into the stack, the original activity is pushed to the second layer of the stack. The change in the position of an activity in the stack reflects its transition between different States. Shows the relationship between the activity status and its position in the stack:

Figure 2. Relationship between the activity status and its position in the stack

As shown above, except for the activity in the active state at the top layer, other activities may be recycled when the system memory is insufficient. The more an activity instance is at the bottom layer of the stack, it is more likely to be recycled by the system. The system is responsible for managing the instances of the activity in the stack. It changes its position in the stack according to the activity status.

Activity Lifecycle

InAndroid. App. ActivityClass, Android defines a series of lifecycle-related methods. In our own activity, we only need to rewrite the required methods as needed, java polymorphism ensures that our methods are called by virtual machines, which is similar to the MIDlet in j2s.

public class OurActivity extends Activity {     protected void onCreate(Bundle savedInstanceState);     protected void onStart();     protected void onResume();     protected void onPause();     protected void onStop();     protected void onDestroy();  }

The methods are described as follows:

      1. Protected void oncreate (bundle savedinstancestate)The first method called when an activity instance is started. In general, we will overwrite this method as an entry point of the application. Here we will do some initialization data and set the user interface. In most cases, we need to load the designed user interface from XML here. For example:
setContentView(R.layout.main); 

Of course, you can alsoSavedinstancestateRead the data we save to the storage device, but you need to determineSavedinstancestateIs itNullBecause no data is stored on the device when the activity is started for the first time:

if(savedInstanceState!=null){  savedInstanceState.get("Key");  }

      1. Protected void onstart ()This method is called after the oncreate () method, or when the activity is switched from stop to active.
      2. Protected void onresume ()Called when the activity is changed from pause to active.
      3. Protected void onresume ()Called when the activity is changed from active to pause.
      4. Protected void onstop ()Called when the activity is switched from active to stop. Generally, the activity status information is saved here.
      5. Protected void ondestroy ()It is called at the end of the active state. It is the last method called at the end of the State. Here, we usually do some work such as releasing resources and clearing the memory.
Figure 3. Call time of these methods

In addition, Android also defines some of the less commonly used life cycle-related methods available:

 protected void onPostCreate(Bundle savedInstanceState);  protected void onRestart();  protected void onPostResume(); 

Android documentation details their calling rules.

It is easy to create an activity in Android. 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 (for the project source code, see download): Activity file:
public class EX01 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();     }  } 

In androidmanifest. XML, you can use the <activity> node to describe activity. After installing the APK file, the system will find and read the activity according to the instructions here. The instructions in this example are as follows:

<activity android:name=".EX01" android:label="@string/app_name">  <intent-filter>  <action android:name="android.intent.action.MAIN" />  <category android:name="android.intent.category.LAUNCHER" />  </intent-filter>  </activity> 

Start another activity

Activity. startactivity ()You can start another activity based on the input parameters:

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

Of course,OtheractivityIt also needs to be defined in androidmanifest. xml.

Intent communication is used for inter-activity communication.

In Android, different activity instances may run in one process or in different processes. Therefore, we need a special mechanism to help us transmit messages between activities. In Android, a message is represented by an intent object. An intent object not only contains the destination of the message, but also the content of the message. This is like an email, which should not only contain the Receiving address, it can also contain specific content. For an intent object, the message "destination" is required, while the content is optional.

In the preceding exampleActivity. startactivity (intent)When starting another activity, we specified the "recipient address" in the intent class constructor ".

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 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? InOtheractivityClassOncreate ()Or use the following code anywhere else to open this "email" and read the information:

Intent intent = getintent (); // receive email bundle = intent. getbundleextra ("key"); // open the email bundle. getboolean ("boolean_key"); // read content bundle. getstring ("string_key ");

We passed the information through the bundle object above. Bundle maintains a hashmap <string, Object> object and stores our data in this hashmap for transmission. But the code like above is a little complicated, because intent has prepared a bundle for us internally, so we can also use this simpler method:
 Intent intent =new Intent(EX06.this,OtherActivity.class);  intent.putExtra("boolean_key", true);  intent.putExtra("string_key", "string_value");  startActivity(intent); 

Receive:

Intent intent=getIntent();  intent.getBooleanExtra("boolean_key",false);  intent.getStringExtra("string_key"); 

Use sharedpreferences

Sharedpreferences uses XML format to provide a permanent data storage method for Android applications. For an android application, it is stored in the file system/Data/your_app_package_name/shared_prefs/Directory, which can be accessed by all the activities in the same application. Android provides related APIs to process the data without requiring programmers to directly operate these files or consider data synchronization issues.

// Write sharedpreferences preferences = getsharedpreferences ("name", mode_private); Editor editor = preferences. edit (); Editor. putboolean ("boolean_key", true); Editor. putstring ("string_key", "string_value"); Editor. commit (); // read sharedpreferences preferences = getsharedpreferences ("name", mode_private); preferences. getboolean ("boolean_key", false); preferences. getstring ("string_key", "default_value ");

Other methods

Android provides many data storage methods including sharedpreferences, such as SQLite and files. programmers can use these APIs to exchange data between activities. If necessary, we can also use the IPC method.

Intent filter of activity

Intent filter describes the intent objects that a component is willing to receive. Android abstracts them into the Android. content. intentfilter class. In the androidmanifest. xml configuration file of Android, you can use<Intent-filter>The node specifies its intent filter for an activity to tell the system what kind of intent the activity can respond.

When a programmer uses startactivity (intent) to start another activity, if the Component Attribute of the intent object is specified directly, activity manager tries to start the activity specified by its component attribute. Otherwise, Android finds the most matched startup from all the activities installed in the system using other intent attributes. If no suitable activity is found, the application will get an exception thrown by the system. The matching process is as follows:

Figure 4. Matching Process of intent filters of activity types


Action matching

Action is a user-defined string used to describe an Android Application Component. An intent filter can contain multiple actions. When androidmanifest. XML activity is defined<Intent-filter>The node specifies an action list to indicate the "actions" that the activity can accept. For example:

<intent-filter >  <action android:name="android.intent.action.MAIN" />  <action android:name="com.zy.myaction" /> …… </intent-filter> 

If we use this intent object when starting an activity:

 Intent intent =new Intent();  intent.setAction("com.zy.myaction"); 

Then, all actions includeCom. ZY. myaction.

Android predefines a series of actions to indicate specific system actions. These actions are defined by constants inAndroid. content. IntentToAction _. You can find detailed descriptions in the documentation provided by Android.

Uri data matching

An intent can carry external data to the target component through the URI. In<Intent-filter>In the node<Data/>Nodes match external data.

The mimetype attribute specifies the data type that carries external data, scheme specifies the protocol, host, port, path specifies the data location, port, and path. As follows:

 <data android:mimeType="mimeType" android:scheme="scheme"  android:host="host" android:port="port" android:path="path"/> 

If these attributes are specified in the intent filter, the URI data match is successful only when all the attributes match successfully.

CATEGORY category match

<Intent-filter>The node can define a category list for the component. If the intent contains all the items in this list, the category match will be successful.

Some tips on activity lock the screen direction during activity running

Android has built-in support for direction sensors. In G1, Android will automatically switch between the portrait screen and landscape Screen Based on the G1 direction. However, sometimes our applications can only run on horizontal or vertical screens, such as some games. At this time, we need to lock the screen direction when the activity is running,<Activity>NodeAndroid: screenorientationProperty to complete this task. The sample code is as follows:

<Activity Android: Name = ". ex01 "Android: Label =" @ string/app_name "Android: screenorientation =" portrait "> // portrait screen. If the value is landscape, the screen is landscape ............ </Activity>

Full Screen Activity

To make an activity run in full screen, you canOncreate ()Add the following code in the method:

// Set the full-screen mode getwindow (). setflags (windowmanager. layoutparams. flag_fullscreen, windowmanager. layoutparams. flag_fullscreen); // remove the title bar requestwindowfeature (window. feature_no_title );

Add progress bars to the activity title

For a more friendly user experience, you can use a progress bar to prompt the user "Don't worry, we are working hard to complete the task you handed over" when processing tasks that take a long time ". For example:

It is a good way to display the progress bar in the Activity title bar. The following is the implementation code:

// The progress bar requestwindowfeature (window. feature_indeterminate_progress); setcontentview (R. layout. main); setprogressbarindeterminatevisibility (true); // clear the progress bar requestwindowfeature (window. feature_progress); setcontentview (R. layout. main); setprogress (5000 );

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.