Detailed Android Activity components

Source: Internet
Author: User

In this paper, the life cycle of activity, communication mode and Intent Filter in Android application programming are introduced in detail, and some techniques and methods of activity are often used in daily development. With this article, you can further connect to how Activity works in Android.

Detailed Android Activity components

Life cycle of Activity

Like J2me's MIDlet, in Android, the lifecycle of Activity is delegated to the system for unified management. Unlike MIDlet, all Activity that is installed on Android is equal.

The state of Activity and the transition between states

In Android, Activity has four basic statuses:

    1. active/runing When a new Activity is launched into the stack, it is at the top of the screen, at the topmost end of the stack, where it is visible and can interact with the user's activation state.
    2. Paused State when activity is overwritten by another transparent or Dialog-style activity. At this point it remains connected to the window manager and the system continues to maintain its internal state, so it is still visible, but it has lost focus and cannot interact with the user.
    3. stoped is in the StopEd state when the activity is overwritten by another activity and the loss of focus is not visible.
    4. killed Activity is killed when the system kills the recycle or is not started.

When an activity instance is created, destroyed, or initiated by another activity, it transitions between these four states, which depend on the action of the user program. Describes the timing and conditions of Activity transitions between different states:

Figure 1. State transitions for Activity

As shown above, Android programmers can determine the "life" of an activity, but cannot determine its "death", it is said that the programmer can start an activity, but can not manually "end" an activity. When you call the Activity.finish () method, the result is the same as when the user presses the back key: tells the activity Manager that the activity instance has completed the corresponding work and can be "recycled". Activity Manager then activates the activity on the second level of the stack and re-enter the stack, while the original activity is pressed into the second layer of the stack, from the active state to the Paused state. For example: Activity2 is started from Activity1, then Activity2 is currently at the top of the stack, and the second layer is Activity1, when we call the Activity2.finish () method, the Activity The Manager reactivated the Activity1 merge stack, Activity2 transitions from the active state stoped state,Activity1. Onactivityresult (int requestcode, int Resultco The DE, Intent data) method is executed, and the Activity2 returned is returned to Activity1 by means of the database parameter.

Activity Stack

Android manages activity through an activity stack, and the state of an activity instance determines its position in the stack. The activity at the foreground is always at the top of the stack, and the activity on the second level of the current station is activated and floats to the top of the stack when it is destroyed by an exception or other reason. When the new activity is launched into the stack, the original activity is pushed into the second layer of the stack. A change in the position of an Activity in the stack reflects its transformation between different states. The state of the Activity is related to its position in the stack as shown:

Figure 2. The state of the Activity and its position in the stack

As shown above, in addition to the top-level active activity, other activity is likely to be recycled when the system is out of memory, the more the instance of an Activity is at the bottom of the stack, the more likely it is to be reclaimed by the system. The system is responsible for managing an instance of the activity in the stack, which changes its position in the stack based on the state in which the activity is located.

Activity life cycle

In the android.app.Activity class, Android defines a series of life-cycle related methods that, in our own Activity, only need to be replicated as needed, Java Polymorphism will ensure that our own method is called by the virtual machine, which is similar to the MIDlet in J2ME.

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 instructions for these methods are as follows:

    1. protected void OnCreate (Bundle savedinstancestate) is the first method that is called when an Activity instance is started. In general, we cover this method as an entry point for the application, where we do some initialization data, set up the user interface, and so on. In most cases, we're going to load a well-designed user interface from XML here. For example:
Setcontentview (R.layout.main);

Of course, we can also read the data we saved to the storage device from savedinstancestate , but we need to determine if savedinstancestate is nullbecause the Activity No data is stored on the device at the first boot:

if (savedinstancestate!=null) {  savedinstancestate.get ("Key");  }
    1. protected void OnStart () The method is called after the OnCreate () method, or when the Activity transitions from the Stop state to the active state.
    2. protected void Onresume () is called when the Activity transitions from the Pause state to the active state.
    3. protected void Onresume () is called when the Activity transitions from the active state to the Pause state.
    4. protected void OnStop () is called when the Activity transitions from the active state to the Stop state. In general, we save the status information of the Activity here.
    5. protected void OnDestroy () is called at the end of the Active operation, which is the last method called at the end, where it is generally done to release resources, clean up memory, and so on.
Figure 3. The timing of the invocation 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 ();

The documentation provided by Android provides a detailed description of their invocation rules.

Create an Activity

Creating an Activity in Android is simple, write a Java class that inherits from Android.app.Activity and declare it in androidmanifest.xml . Here is an activity instance to study the activity life cycle.

Activity file:

 public class EX01 extends Activity {private static final String Log_tag = EX01.class.getSim     Plename ();              @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 (); }  }

Androidmanifest.xml in the <activity> node description activity, after installing the APK file, the system according to the instructions here to find read activity, in this example, the instructions 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

The activity.startactivity () method initiates another Activity based on the parameters that are passed in:

Intent Intent =new Intent (currentactivity.this,otheractivity.class);  StartActivity (Intent);

Of course,otheractivity also needs to be defined in Androidmanifest.xml.

Communication between Activity using Intent communication

In Android, different Activity instances may run in a process, or they may run in different processes. So we need a special mechanism to help us deliver messages between the Activity. In Android, a message is represented by a Intent object, a Intent object that contains not only the destination of the message, but also the content of the message, which is like an email, which should include not only the address of the recipient, but also the specific content. For a Intent object, the message "destination" is required, while the content is optional.

In the above example, with activity. StartActivity (Intent) when another activity is started, we specify "recipient address" in the constructor of the intent class.

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

Intent Intent =new Intent (currentactivity.this,otheractivity.class);  Create an email  bundle bundle =new Bundle () with "recipient address",//Create email content bundle.putboolean ("Boolean_key", true);//write Content Bundl E.putstring ("String_key", "string_value");  Intent.putextra ("key", bundle);//Package Email  startactivity (intent);//Start new Activity

So how does the recipient receive the letter? Use the following code in onCreate () or anywhere else in the otheractivity class to open this "e-mail" to read the information:

Intent Intent =getintent ();//Receive email  bundle bundle =intent.getbundleextra ("key");//Open Email  Bundle.getboolean ("Boolean_key");//Read content bundle.getstring ("String_key");

Above we pass the information through the bundle object,bundle maintains a hashmap<string, object> object, storing our data in this HASHMAP To be passed in. But the code like the one above is a little more complicated, because Intent has a bundlein it for us, so we can also use this simpler approach:

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");
Using Sharedpreferences

Sharedpreferences uses an XML format to provide a permanent means of data storage for Android applications. For an Android application, it is stored in the /data/data/your_app_package_name/shared_prefs/ directory of the file system and can be accessed by all activity in the same application. Android provides the relevant API to process this data without requiring programmers to manipulate these files directly or to consider data synchronization issues.

Write sharedpreferences  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  sharedpreferences preferences = getsharedpreferences ("name", mode_private);  Preferences.getboolean ("Boolean_key", false);  Preferences.getstring ("String_key", "default_value");
Other ways

Android provides a variety of data storage methods, including sharedpreferences, such as SQLite, files, etc., which programmers can use to enable data exchange between Activity. If necessary, we can also use the IPC method.

Intent Filter for Activity

Intent Filter describes what kind of Intent objects a component is willing to receive, and Android abstracts it into a Android.content.IntentFilter class. In Android's androidmanifest.xml configuration file, you can specify its intent filter for an Activity via the <intent-filter > node to tell the system that the Activit Y can respond to what type of Intent.

When a programmer uses startactivity (intent) to start another Activity, if you specify intent the Component property of the object directly, then Activity Manager will attempt to start its Component property specified by the Activity. Otherwise, Android will find the most matching boot from all the activity installed in the system via the other properties of Intent, and the application will get an exception thrown by the system if no suitable activity is found. The process for this match is as follows:

Figure 4. The matching process of Activity species Intent Filter

Action match

The action is a user-defined string that describes an Android application component, and a Intent Filter can contain more than one Action. In the Androidmanifest.xml activity definition, you can specify an action list at its <intent-filter > node to indicate the "action" 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 such a Intent object when we start an Activity:

Intent Intent =new Intent ();  Intent.setaction ("Com.zy.myaction");

All Activity that contains the "com.zy.myaction" in the Action list will match successfully.

Android pre-defines a series of actions that represent a specific system action, respectively. These actions are defined in a constant way in the android.content. Intent , start with "action_". We can find detailed descriptions of them in the documentation provided by Android.

URI Data Matching

A Intent can carry external data to the target component via a URI. In the <intent-filter > node, the external data is matched through the <data/> node.

The MimeType property specifies the data type that carries the external data, scheme specifies the protocol, host, port, path specifies the location of the data, port, and paths. As follows:

<data android:mimetype= "MimeType" android:scheme= "scheme"  android:host= "host" android:port= "Port" Android: Path= "Path"/>

If these properties are specified in the Intent Filter, then only the URI data match succeeds if all of the properties match successfully.

Category match

<intent-filter > Node A category category list can be defined for the component, and the category class match will be successful when all the items in the intent are included in the list.

Some tricks on activity lock the screen orientation of the Activity runtime

Android has built-in support for directional sensors. In G1, Android automatically switches between the vertical screen and the horizontal screen, depending on the direction in which the G1 is located. But sometimes our app can only run on a horizontal screen/vertical screen, such as some games, where we need to lock the screen orientation of the Activity runtime,<activity > node android: The Screenorientation property can accomplish this task, as shown in the sample code:

<activity android:name= ". EX01 "android:label=" @string/app_name "  android:screenorientation=" Portrait ">//vertical screen with a value of landscape for horizontal screen ... < /activity>
Full-screen Activity

To make an Activity run in full screen, you can add the following code in its onCreate () method:

Set full-screen mode GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN,     WindowManager.LayoutParams.FLAG_ fullscreen);  Remove title bar requestwindowfeature (Window.feature_no_title);
Add a progress bar to the Title of the Activity

For a more user-friendly experience, you can use a progress bar to prompt the user "Don't worry, we're trying to finish the task you gave" when dealing with tasks that take a long time. Such as:

It's a good idea to show the progress bar in the Activity's title bar, and here's the implementation code:

Unclear progress bar requestwindowfeature (window.feature_indeterminate_progress);  Setcontentview (r.layout.main);  Setprogressbarindeterminatevisibility (true);  Clear progress bar requestwindowfeature (window.feature_progress);  Setcontentview (r.layout.main);  Setprogress (5000);

This article goes from http://www.ibm.com/developerworks/cn/opensource/os-cn-android-actvt/, thanks to the author for sharing

Detailed Android Activity components

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.