Android activity and intent Mechanism

Source: Internet
Author: User
Tags call back home screen
Activity

In Android, activity is the foundation of all programs, and the processes of all programs run in activity. activity has its own life cycle (see activities ).

For an activity, the key is its life cycle (for example,), followed by the state storage and recovery (onsaveinstancestate onrestoreinstancestate), and inter-activity jump and data transmission (intent ).

Common functions in activity include setcontentview () findviewbyid () finish () startactivity (). The following are the functions involved in the lifecycle:

Void oncreate (bundle savedinstancestate)
Void onstart ()
Void onrestart ()
Void onresume ()
Void onpause ()
Void onstop ()
Void ondestroy ()

Note that you must add the corresponding <activity> in the manifest file and set its attributes and intent-filter to use the activity.

Intent

Android provides an intent mechanism to assist in interaction and communication between applications. Intent describes the actions, actions involving data, and additional data of an application, android finds the corresponding component based on the description of the intent, passes the intent to the called component, and calls the component. Intent can be used not only between applications, but also between activities/services within the application. Therefore, intent acts as a media intermediary here, providing information about component calls to each other to decouple callers from callers. The function of intent is shown in the SDK as follows:

Start an activity through context. startactivity () implements tietong. startactivityforresult;
Start a service through context. startservice (), or use context. bindservice () to interact with the background service;
Send the broadcast method (such as context. sendbroadcast (), context. sendorderedbroadcast (), and context. sendstickybroadcast () to broadcast receivers.
Intent attribute settings include the following: (The following are definitions in XML, and can also be obtained and set using the intent class method)

(1) action, that is, the action to be executed

The SDK defines some standard actions, including

Onstant target component action
Action_call activity initiate a phone call.
Action_edit activity display data for the user to edit.
Action_main Activity start up as the initial activity of a task, with no data input and no returned output.
Action_sync activity synchronize data on a server with data on the mobile device.
Action_battery_low broadcast multicast er a warning that the battery is low.
Action_headset_plug broadcast receiver er a headset has been plugged into the device, or unplugged from it.
Action_screen_on broadcast receiver er the screen has been turned on.
Action_timezone_changed broadcast receiver er the setting for the time zone has changed.

Of course, you can also customize the action (when using a custom action, you need to add the package name as the prefix, such as "com. example. project. show_color), and you can define the corresponding activity to process our custom actions.

(2) data, that is, the data to be operated by the execution action

Android uses a URI pointing to data. For example, in a contact application, a URI pointing to a contact may be: Content: // contacts/1. For different actions, the URI data type is different (you can set the type attribute to specify a specific type of data). For example, action_edit specifies that data is the file URI and calls Tel: URI, the access network is http: URI, while the data provided by the content provider is content: Uris.

(3) type (data type), explicitly specifying the intent data type (MIME ). Generally, the intent data type can be determined based on the data itself. However, by setting this attribute, You can forcibly use the explicitly specified type instead of derivation.

(4) category (category): additional information about the executed action. For example, launcher_category indicates that the receiver of intent should appear as a top-level application in launcher, while alternative_category indicates that the current intent is one of a series of optional actions that can be executed on the same piece of data. There are other

Constant meaning
Category_browsable the target activity can be safely invoked by the browser to display data referenced by a link-for example, an image or an e-mail message.
Category_gadget the activity can be embedded inside of another activity that hosts gadgets.
Category_home the activity displays the home screen, the first screen the user sees when the device is turned on or when the home key is pressed.
Category_launcher the activity can be the initial activity of a task and is listed in the top-level application launcher.
Category_preference the target activity is a preference panel.

(5) component: Specifies the Class Name of the intent's target component. Generally, Android searches for other attributes in intent, such as action, data/type, and category, and finds a matched target component. However, if this attribute of component is specified, the component specified by component will be used directly without executing the above search process. After this attribute is specified, all other intent attributes are optional.

(6) extras (additional information) is a collection of all other additional information. You can use extras to provide extended information for components. For example, if you want to perform the "send email" action, you can save the email title and body in extras, send to the email sending component.

One of the keys to understanding intent is to understand the two basic usage of intent: an explicit intent, that is, specifying the receiver when constructing the intent object; the other is an implicit intent, that is, when the intent sender constructs an intent object, it does not know or care about who the receiver is. This helps reduce the coupling between the sender and the receiver.

Android does not need to parse explicit intent because the target component is clear. Android needs to parse implicit intent, map intent to the activity, intentreceiver, or service that can process the intent.

The intent parsing mechanism mainly finds the matching intent by finding all intentfilters registered in androidmanifest. XML and the intent defined in them. In this parsing process, Android uses the intent action, type, and category attributes to determine the attributes. The judgment method is as follows:

If intent specifies an action, the action must be included in the intentfilter action list of the target component; otherwise, the action cannot be matched;
If the intent does not provide a type, the system obtains the data type from the data. Like action, the Data Type list of the target component must contain the intent data type. Otherwise, the data type does not match.
If the data in the intent is not a content: Type Uri and the intent does not explicitly specify its type, it will match according to the scheme (such as http: or mailto :) of the data in the intent. Similarly, the scheme of intent must appear in the scheme list of the target component.
If intent specifies one or more category categories, these categories must all appear in the Set category list. For example, intent contains two categories: launcher_category and alternative_category. The parsed target component must contain at least these two categories.
Intent-filter Definition

Examples of setting attributes:

<Action Android: Name = "com. example. Project. show_current"/>
<Category Android: Name = "android. Intent. Category. Default"/>
<Data Android: mimetype = "Video/MPEG" Android: Scheme = "HTTP".../>
<Data Android: mimetype = "image/*"/>
<Data Android: Scheme = "HTTP" Android: TYPE = "Video/*"/>
Complete instance

<Activity Android: Name = "noteslist" Android: Label = "@ string/title_notes_list"> <intent-filter> <action Android: Name = "android. intent. action. main "/> <category Android: Name =" android. intent. category. launcher "/> </intent-filter> <action Android: Name =" android. intent. action. view "/> <action Android: Name =" android. intent. action. edit "/> <action Android: Name =" android. intent. action. pick "/> <category Android: Name =" android. intent. category. default "/> <data Android: mimetype =" Vnd. android. cursor. DIR/vnd. google. note "/> </intent-filter> <action Android: Name =" android. intent. action. get_content "/> <category Android: Name =" android. intent. category. default "/> <data Android: mimetype =" Vnd. android. cursor. item/vnd. google. note "/> </intent-filter> </activity>
Intent usage instance

1. No parameter for activity jump

Intent it = new intent (activity. Main. This, activity2.class );
Startactivity (it );

2. pass data to the next activity (use bundle and intent. putextras)

Intent it = new intent (activity. Main. This, activity2.class );
Bundle bundle = new bundle ();
Bundle. putstring ("name", "this is from mainactivity! ");
It. putextras (bundle); // it. putextra ("test", "shuju ");
Startactivity (it); // startactivityforresult (it, request_code );

You can use the following methods to obtain data:

Bundle bundle = getintent (). getextras ();
String name = bundle. getstring ("name ");

3. Return the result to the previous activity (use setresult to start the activity for startactivityforresult (it, request_code)

Intent intent = getintent ();
Bundle bundle2 = new bundle ();
Bundle2.putstring ("name", "this is from showmsg! ");
Intent. putextras (bundle2 );
Setresult (result_ OK, intent );

4. Call back the result processing function (onactivityresult) of the previous activity)

@ Override
Protected void onactivityresult (INT requestcode, int resultcode, intent data ){
// Todo auto-generated method stub
Super. onactivityresult (requestcode, resultcode, data );
If (requestcode = request_code ){
If (resultcode = result_canceled)
Settitle ("cancle ");
Else if (resultcode = result_ OK ){
String temp = NULL;
Bundle bundle = data. getextras ();
If (bundle! = NULL) temp = bundle. getstring ("name ");
Settitle (temp );
}
}
}

The following are some other intent usage examples (from javaeye)

Display webpage
1. Uri uri = URI. parse ("http://google.com ");
2. Intent it = new intent (intent. action_view, Uri );
3. startactivity (it );

Show Map
1. Uri uri = URI. parse ("Geo: 38.899533,-77.036476 ");
2. Intent it = new intent (intent. action_view, Uri );
3. startactivity (it );
4. // other geo uri examples
5. // GEO: latitude, longpolling
6. // GEO: latitude, longpolling? Z = zoom
7. // GEO: 0, 0? Q = My + street + address
8. // GEO: 0, 0? Q = business + near + city
9. // Google. Streetview: cbll = Lat, LNG & white = 1, yaw, pitch, zoom & MZ = mapzoom

Route Planning
1. Uri uri = URI. parse ("http://maps.google.com/maps? F = D & saddr = startlat % 20 startlng & daddr = endlat % 20 endlng & HL = EN ");
2. Intent it = new intent (intent. action_view, Uri );
3. startactivity (it );
4. // Where startlat, startlng, endlat, endlng are a long with 6 decimals like: 50.123456

Call
1. // call the dialing program
2. Uri uri = URI. parse ("Tel: 0800000123 ");
3. Intent it = new intent (intent. action_dial, Uri );
4. startactivity (it );
1. // directly call
2. Uri uri = URI. parse ("Tel: 0800000123 ");
3. Intent it = new intent (intent. action_call, Uri );
4. startactivity (it );
5. // use this file, which must be added to androidmanifest. xml.
6. // <uses-Permission id = "android. Permission. call_phone"/>

Send SMS/MMS
1. // call the SMS Program
2. Intent it = new intent (intent. action_view, Uri );
3. It. putextra ("sms_body", "the SMS text ");
4. It. settype ("Vnd. Android-DIR/MMS-SMS ");
5. startactivity (it );
1. // send messages
2. Uri uri = URI. parse ("smsto: // 0800000123 ");
3. Intent it = new intent (intent. action_sendto, Uri );
4. It. putextra ("sms_body", "the SMS text ");
5. startactivity (it );
1. // send MMS
2. Uri uri = URI. parse ("content: // media/external/images/Media/23 ");
3. Intent it = new intent (intent. action_send );
4. It. putextra ("sms_body", "some text ");
5. It. putextra (intent. extra_stream, Uri );
6. It. settype ("image/PNG ");
7. startactivity (it );

Send email
1. Uri uri = URI. parse ("mailto: xxx@abc.com ");
2. Intent it = new intent (intent. action_sendto, Uri );
3. startactivity (it );

1. Intent it = new intent (intent. action_send );
2. it. putextra (intent. extra_email, "me@abc.com ");
3. It. putextra (intent. extra_text, "the email body text ");
4. It. settype ("text/plain ");
5. startactivity (intent. createchooser (IT, "Choose email client "));

1. Intent it = new intent (intent. action_send );
2. String [] TOS = {"me@abc.com "};
3. String [] CCS = {"you@abc.com "};
4. It. putextra (intent. extra_email, TOS );
5. It. putextra (intent. extra_cc, CCS );
6. It. putextra (intent. extra_text, "the email body text ");
7. It. putextra (intent. extra_subject, "the email subject text ");
8. It. settype ("message/rfc822 ");
9. startactivity (intent. createchooser (IT, "Choose email client "));

1. // transfer the attachment
2. Intent it = new intent (intent. action_send );
3. It. putextra (intent. extra_subject, "the email subject text ");
4. It. putextra (intent. extra_stream, "file: // sdcard/mysong.mp3 ");
5. sendintent. settype ("audio/MP3 ");
6. startactivity (intent. createchooser (IT, "Choose email client "));

Play multimedia
Uri uri = URI. parse ("file: // sdcard/song.mp3 ");
Intent it = new intent (intent. action_view, Uri );
It. settype ("audio/MP3 ");
Startactivity (it );
Uri uri = URI. withappendedpath (mediastore. Audio. Media. internal_content_uri, "1 ");
Intent it = new intent (intent. action_view, Uri );
Startactivity (it );

Market Problems
1. // search for an application
2. Uri uri = URI. parse ("Market: // search? Q = pname: pkg_name ");
3. Intent it = new intent (intent. action_view, Uri );
4. startactivity (it );
5. // Where pkg_name is the full package path for an application
1. // display information about an application
2. Uri uri = URI. parse ("Market: // details? Id = app_id ");
3. Intent it = new intent (intent. action_view, Uri );
4. startactivity (it );
5. // Where app_id is the Application ID, find the ID
6. // by clicking on your application on market Home
7. // page, and notice the ID from the address bar

Uninstall Application
1. Uri uri = URI. fromparts ("package", strpackagename, null );
2. Intent it = new intent (intent. action_delete, Uri );
3. startactivity (it );

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.