Android Intent Mechanism and sample summary (summary article) _android

Source: Internet
Author: User
Tags home screen

Recently, in the course of Android development, it is difficult to pass the intent to the calling component and complete the component invocation, and intent learning is a little bit of knowledge, and recently took some time for this, the intent part of the systematic learning and some practice, The following will be their own learning and intent knowledge of the detailed induction, hoping to help the same problem with the Bo friends.

The following is a summary of intent introduction, detailed and intent examples:

I. Intent Introduction:

Intent's Chinese meaning is "intention, intention", in Android provides a intent mechanism to assist the application of interaction and communication, intent is responsible for the application of the action, action involved in data, additional data description, Android according to this intent description, Responsible for finding the corresponding component, passing the intent to the calling component and completing the component invocation. Intent can be used not only between applications, but also between activity/service within applications. As a result, the "media" that intent understands to communicate between different components specifically provides information about what components call each other.

Second, intent function:

Intent is an abstract description of the action to be performed, typically used as a parameter, by Intent to assist in the communication between the various components of the Android. For example, call StartActivity () to start an activity, or by broadcaseintent () to all interested broadcasereceiver, or by StartService ()/ Bindservice () to start a backend service. So it can be seen that intent is primarily used to initiate other activity or service, so that intent can be understood as a binder between activity.

Three. Inten the method of starting the component:

Intent can start an activity, start a service, and initiate a broadcast broadcasts. The specific methods are as follows:

Component Name

Method name

Activity

Startactvity ()

StartActivity ()

Service

StartService ()

Bindservice ()

Broadcasts

Sendbroadcasts ()

Sendorderedbroadcasts ()

Sendstickybroadcasts ()

Four. Several important attributes of intent are detailed below:

Actions, data, categories (Category), types (type), components (compent), and extension letters (EXTRA). The most common of these is the action attribute and the Data property.

1.Action Properties:

For an activity with the following declaration:

<activity android:name= ". Targetactivity "> 
<intent-filter> 
<action android:name=" Com.scott.intent.action.TARGET "/> 
<category android:name= "Android.intent.category.DEFAULT"/> 
</intent-filter> 

Targetactivity the <action> in its <intent-filter>, the target action, and if we need to do a jump action, we need to specify the action of the target in intent, as follows:

public void gototargetactivity (view view) { 
Intent Intent = new Intent ("Com.scott.intent.action.TARGET"); 
StartActivity (Intent); 

When we specify the appropriate action for intent, and then call the StartActivity method, the system jumps to the corresponding activity according to the action.

In addition to the custom action, intent also contains a number of default action, listed below:

public static final String Action_main = "Android.intent.action.MAIN"; 
public static final String Action_view = "Android.intent.action.VIEW"; 
public static final String Action_web_search = "Android.intent.action.WEB_SEARCH"; 

Each action has its specific purpose.

2.data and Extras, the data to be manipulated by the action and additional information to be delivered to the target:

Here's an example of interacting with a browser:

/** 
* Open the specified page 
* @param view/public 
void Invokewebbrowser (view view) { 
Intent Intent = new Intent (in Tent. Action_view); 
Intent.setdata (Uri.parse ("http://www.google.com.hk")); 
StartActivity (intent); 
} 
/** 
* Keyword search 
* @param view/public 
void Invokewebsearch (view view) { 
Intent Intent = new inte NT (intent.action_web_search); 
Intent.putextra (Searchmanager.query, "Android"); Keywords 
startactivity (intent); 

The above two methods are to start the browser and open the specified Web page, keyword search, the corresponding ACTION is Intent.action_view and Intent.action_web_search, the former need to specify the corresponding Web page address, the latter need to specify keyword information, For keyword searches, browsers search by default search engines set by themselves.

We note that when you open a Web page, specify a data property for intent, which is actually specifying what you want to manipulate, which is the form of a URI, where we can convert a string of the specified prefix to a specific URI type, such as "http:" or "https:" for the network address type, " Tel: "Indicates the type of phone number," mailto: "indicates the type of mail address, and so on.

For example, to call a given number, you can do this:

public void call (view view) { 
Intent Intent = new Intent (intent.action_call); 
Intent.setdata (Uri.parse ("Tel:")); 
StartActivity (Intent); 

So how do we know if the target accepts this prefix? This requires a look at the matching rules for the <data/> elements in the target.

The following seed elements are included in the target <data/> tag, and they define the matching rules for the URL:

Android:scheme matches the prefix in the URL, except "http", "https", "tel" ... Besides, we can define our own prefixes.

Android:host matches the host name portion of the URL, such as "google.com", or any host name if defined as "*"

Android:port matches the port in the URL

Android:path matches the path in the URL

Let's change the Targetactivity declaration information:

<activity android:name= ". Targetactivity "> 
<intent-filter> 
<action android:name=" Com.scott.intent.action.TARGET "/> 
<category android:name= "Android.intent.category.DEFAULT"/> 
<data android:scheme= "Scott" Android : host= "Com.scott.intent.data" android:port= "" android:path= "/target"/> 
</intent-filter> 

This time if only the action is specified is not enough, we need to set the data value for it, as follows:

Constant
Explain
Category_default
The default category
Category_browsable
After you specify this category, when you click on a picture or link on a Web page, the system considers the target activity to be included in the optional list for the user to choose to open the picture or link.
Category_gadget
The activity can be embedded inside of another, the hosts gadgets.
Category_home
The activity displays the "Home" screen, the "The" sees when the device is turned on or the home key is Pressed.
Category_launcher
The activity can are the initial activity of a task and are listed in the top-level Application launcher.
Category_preference
Indicates that the target activity is a preference interface;

public void gototargetactivity (view view) { 
Intent Intent = new Intent ("Com.scott.intent.action.TARGET"); 
Intent.setdata (Uri.parse ("Scott://com.scott.intent.data:/target")); 
StartActivity (intent); 
}

At this point, each part of the URL and the Targetactivity configuration information are all consistent in order to jump successfully, otherwise it will be rejected by the system.

But sometimes it's not good to have a path limit, like we have a URL like this: (Scott://com.scott.intent.data:7788/target/hello) (scott://com.scott.intent.data : 7788/target/hi) What should I do at this time? We need to use another element: Android:pathprefix, which represents the path prefix. We modify the android:path= "/target" to android:pathprefix= "/target", and then we can meet the above requirements. And in the search, we used a Putextra method, the keyword as a parameter placed in the intent, we become extras (additional information), which involves a bundle object.

Bundle and intent have a close relationship, mainly responsible for the intent to save additional parameter information, it implements the Android.os.Paracelable interface, the internal maintenance of a map type of properties, used in the form of key-value pairs to store additional parameter information. When we place additional information using the intent Putextra method, the method checks that the default bundle instance is not null and, if it is empty, creates a new bundle instance, and then places the specific parameter information in the bundle instance. We can also create bundle objects ourselves, and then specify this bundle for intent, as follows:

public void gototargetactivity (view view) { 
Intent Intent = new Intent ("Com.scott.intent.action.TARGET"); 
Bundle Bundle = new Bundle (); 
Bundle.putint ("id",); 
Bundle.putstring ("name", "Scott"); 
Intent.putextras (bundle); 
StartActivity (intent); 
}

Note that after you use the Putextras method to set the bundle object, the system is not a reference operation, but a copy operation, so if you change the data in the bundle instance after you set it up, you will not affect additional information within intent. So how do we get additional information that is set in the intent? In this case, we're going to get the bundle instance from the intent, and then we'll take the corresponding key value information out of it:

Bundle Bundle = Intent.getextras (); 
int id = bundle.getint ("id"); 

Of course, we can also use the intent Getintextra and Getstringextra methods to get the data source is the bundle type of instance object in intent.

The trait or behavior of a target that performs an action, 3.category.

For example: In our application the main interface activity usually has the following configuration:

 
 

Represents the target activity as the initial activity in the task in which the application resides and appears in the application list of the system launcher.

A few common category are as follows:

When you set up category for intent, you should use the Addcategory (String category) method to add the specified category information to the intent to match the target activity that declares this category.

Here's an example of going back to the home screen:

Main.xml:

 <?xml version= "." Encoding= "utf-"?> <linearlayout xmlns:android= 
 "http://schemas.android.com/apk/res/ Android " 
 android:orientation=" vertical "android:layout_width=" fill_parent " 
 android:layout_height=" Fill_ Parent " 
 > 
 <textview 
 android:layout_width=" fill_parent " 
 android:layout_height=" Wrap_ Content " 
 android:text=" test Intent Category " 
 /> 
 <button 
 android:id=" @+id/button " Android:layout_width= "Wrap_content" 
 android:layout_height= "wrap_content" 
 android:text= "go to the Home interface" 
 /> 
 

Strings.xml:

 <?xml version= "." Encoding= "utf-"?> 
 <resources> 
 <string name= "Hello" >hello world, mainactivity!</string> 
 <string name= "App_name" >IntentCategoryDemo</string> 
 

Mainactivity.java:

 Package com.android.category.activity; 
 Import android.app.Activity; 
 Import android.content.Intent; 
 Import Android.os.Bundle; 
 Import Android.view.View; 
 Import Android.view.View.OnClickListener; 
 Import Android.widget.Button; 
 public class Mainactivity extends activity { 
 private Button btn; 
 @Override public 
 void OnCreate (Bundle savedinstancestate) { 
 super.oncreate (savedinstancestate); 
 Setcontentview (r.layout.main); 
 BTN = (Button) Findviewbyid (R.id.button); 
 Btn.setonclicklistener (New Onclicklistener () { 
  @Override public 
  void OnClick (View v) { 
  Intent Intent = New Intent ();  
  Intent.setaction (Intent.action_main);//Add ACTION attribute 
  intent.addcategory (intent.category_home);//Add CATEGORY Property 
  startactivity (intent);/start Activity 
  } 
 }); 
  
 

The effect chart is as follows:


Home:

4.type: MIME data types that can be handled by the target activity to perform the action

For example, a target activity that can process a picture contains such mimetype in its declaration:

 
 

When matching using intent, we can use Settype (string type) or Setdataandtype (Uri data, String type) to set the mimetype.

5.component, package or class name of the target component

When using component for matching, the following are generally used:

 Intent.setcomponent (New ComponentName (Getapplicationcontext (), Targetactivity.class)); 
 Intent.setcomponent (New ComponentName (Getapplicationcontext (), "com.scott.intent.TargetActivity")); 
 Intent.setcomponent (New ComponentName ("Com.scott.other", "com.scott.other.TargetActivity"));

The first two are used to match targets within the same package, and the third is to match targets within other packages.

"Note": If we specify the component attribute in intent, the system will no longer match action, Data/type, category.

Five, Intent usage example Comprehensive summary:

1. Call Dialing Program

 Call the mobile service
 uri uri = Uri.parse ("tel:");
 Intent Intent = new Intent (intent.action_dial, URI);
 

2. Send SMS or MMS

To send the message "Hello" SMS
 uri uri = Uri.parse ("Smsto:");
 Intent Intent = new Intent (intent.action_sendto, URI);
 Intent.putextra ("Sms_body", "Hello");
 StartActivity (intent); 
 Send MMS (equivalent to send SMS with attachment)
 Intent Intent = new Intent (intent.action_send);
 Intent.putextra ("Sms_body", "Hello");
 Uri uri = uri.parse ("content://media/external/images/media/");
 Intent.putextra (Intent.extra_stream, URI);
 Intent.settype ("Image/png");
 

3. Open Web page through browser

Open the Google homepage uri uri = uri.parse ("http://www.google.com");
 Intent Intent = new Intent (Intent.action_view, URI); 
StartActivity (Intent);
 Send email//To someone@domain.com email uri uri = uri.parse ("mailto:someone@domain.com");
 Intent Intent = new Intent (intent.action_sendto, URI); 
 StartActivity (Intent);
 Send mail to someone@domain.com Intent Intent = new Intent (intent.action_send) with the content "Hello";
 Intent.putextra (Intent.extra_email, "someone@domain.com");
 Intent.putextra (Intent.extra_subject, "SUBJECT");
 Intent.putextra (Intent.extra_text, "Hello");
 Intent.settype ("Text/plain"); 
 StartActivity (Intent);
 Email Intent intent=new Intent (intent.action_send) to multiple people; String[] tos = {"@abc. com", "@abc. com"}; Recipient string[] CCS = {"@abc. com", "@abc. com"}; CC string[] BCCs = {"@abc. com", "@abc. com"};
 Dense send Intent.putextra (intent.extra_email, TOS);
 Intent.putextra (INTENT.EXTRA_CC, CCS);
 Intent.putextra (INTENT.EXTRA_BCC, BCCs);
 Intent.putextra (Intent.extra_subject, "SUBJECT"); Intent.Putextra (Intent.extra_text, "Hello");
 Intent.settype ("Message/rfc");  StartActivity (Intent);

5. Display map and path planning

Open Google Map China Beijing location (northern latitude, longitude.)
 uri uri = Uri.parse ("Geo:.,.");
 Intent Intent = new Intent (Intent.action_view, URI);
 StartActivity (intent); 
 Path planning: From Somewhere in Beijing (northern latitude, longitude.) to a place in Shanghai (northern latitude, longitude.)
 uri uri = Uri.parse ("http://maps.google.com/maps?f=d&saddr=. &daddr=. .");
 Intent Intent = new Intent (Intent.action_view, URI);
 StartActivity (Intent);

6. Play Multimedia

 Intent Intent = new Intent (intent.action_view);
 Uri uri = uri.parse ("file:///sdcard/foo.mp");
 Intent.setdataandtype (URI, "AUDIO/MP");
 StartActivity (intent);
 Uri uri = Uri.withappendedpath (MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "");
 Intent Intent = new Intent (Intent.action_view, URI);
 

7. Take photos

 Open the camera program
 Intent Intent = new Intent (mediastore.action_image_capture);
 Startactivityforresult (Intent,); 
 Take out the photo data
 Bundle extras = Intent.getextras ();
 

8. Get and cut pictures

 Get and cut the picture Intent Intent = new Intent (intent.action_get_content);
 Intent.settype ("image/*"); Intent.putextra ("Crop", "true"); Open Shear Intent.putextra ("Aspectx",);
 The ratio of the shear width to height is: Intent.putextra ("aspecty"); Intent.putextra ("Outputx",);
 Save picture width and height intent.putextra ("outputy",); Intent.putextra ("Output", Uri.fromfile (New File ("/mnt/sdcard/temp")); 
 Save path Intent.putextra ("OutputFormat", "JPEG");//return format Startactivityforresult (intent,);
 Cut specific picture Intent Intent = new Intent ("Com.android.camera.action.CROP");
 Intent.setclassname ("Com.android.camera", "com.android.camera.CropImage");
 Intent.setdata (Uri.fromfile) (New File ("/mnt/sdcard/temp")); Intent.putextra ("Outputx",);
 The ratio of the shear width to height is: Intent.putextra ("outputy"); Intent.putextra ("Aspectx",);
 Save picture width and height intent.putextra ("aspecty",);
 Intent.putextra ("scale", true);
 Intent.putextra ("Nofacedetection", true);
 Intent.putextra ("Output", Uri.parse ("file:///mnt/sdcard/temp"));  Startactivityforresult (Intent,);

9. Open Google Market

Open Google market directly into the program's detailed page
 uri uri = uri.parse ("market://details?id=" + "Com.demo.app");
 Intent Intent = new Intent (Intent.action_view, URI);
 

10. Installation and Uninstall procedures

 Uri uri = uri.fromparts ("package", "Com.demo.app", null);
 Intent Intent = new Intent (Intent.action_delete, URI);
 

11. Enter the Setup interface

Enter the wireless network Setup interface (others can be extrapolate)
 Intent Intent = new Intent (Android.provider.Settings.ACTION_WIRELESS_SETTINGS);
 Startactivityforresult (Intent,);

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.