I. Intent Introduction:
Intent's Chinese meaning is "intention, intention", in Android provides the intent mechanism to assist the interaction between the application and communication, intent is responsible for the application of the action, the action involved in data, additional data description, Android according to this intent description, Responsible for locating the corresponding component, passing the intent to the calling component, and completing the call to the component. Intent can be used not only between applications, but also between Activity/service within an application. As a result, intent can be understood as a "medium" for communication between different components, specifically providing information about what components call each other.
Second, intent effect:
Intent is an abstract description of the action to be performed, which is generally used as a parameter, and is assisted by Intent to complete communication between the various components of Android. For example, call StartActivity () to initiate an activity, or 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 intent can be understood as an adhesive between the activity.
Three. Inten how to start the component:
Intent can start an activity, start a service, and initiate a broadcast broadcasts. Here's how:
Component Name |
Method name |
Activity |
Startactvity () StartActivity () |
Service |
StartService () Bindservice () |
Broadcasts |
Sendbroadcasts () Sendorderedbroadcasts () Sendstickybroadcasts () |
Four. Several important attributes of intent, which are explained below:
Action, data, category, type, Component (Compent), and extended letter (Extra). The most common of these are the Action property and the Data property.
1.Action Properties:
For 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> </ Activity>
Targetactivity declared <action> in its <intent-filter>, that is, the target action, if we need to do a jump action, we need to specify the target action 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 based on the action.
In addition to the custom action, intent contains a number of default actions, which are 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"; public static final String Action_call = "Android.intent.action.CALL";
Each action has its specific purpose.
2.data and extras, which is the data to be manipulated by the action and additional information passed 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 Inten T (intent.action_web_search); Intent.putextra (Searchmanager.query, "Android"); Keyword startactivity (intent); }
The above two methods are to launch the browser and open the specified page, the keyword search, the corresponding ACTION is Intent.action_view and Intent.action_web_search, the former need to specify the corresponding page address, the latter need to specify the keyword information, For keyword search, the browser will search by default search engine set by itself.
We notice that when you open a Web page, you specify a data property for intent, which is actually specifying what to manipulate, which is the form of a URI, and 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 phone number type," mailto: "indicates the type of mail address, and so on.
For example, to call a given number, we can do this:
public void call (view view) { Intent Intent = new Intent (intent.action_call); Intent.setdata (Uri.parse ("tel:12345678")); 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 targets <data/> tags, and they define the matching rules for the URLs:
android:scheme matches the prefix in the URL, except for "http", "https", "tel" ... , we can define our own prefixes.
android:host matches the hostname part of the URL, such as "google.com", if it is defined as "*" to indicate any host name
Android:port matching a port in a URL
Android:path matches the path in the URL
Let's change the targetactivity statement 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= "7788" android:path= "/target"/> </intent-filter> </activity>
It is not enough to specify the action at this time, we need to set the data value for it, as follows:
public void gototargetactivity (view view) { Intent Intent = new Intent ("Com.scott.intent.action.TARGET"); Intent.setdata (Uri.parse ("Scott://com.scott.intent.data:7788/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 is rejected by the system.
However, sometimes it is not very good to limit the path to death, for example, we have such a URL: (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 change the android:path= "/target" to android:pathprefix= "/target", and then we can meet the above requirements. While searching, we used a Putextra method to place the keyword as a parameter in intent, and we became extras (additional information), which involved a bundle object.
Bundles and intent have an inseparable relationship, the main responsibility for intent to save additional parameter information, it implements the Android.os.Paracelable interface, internal maintenance of a map type of properties, for the form of key-value pairs to store additional parameter information. When we use intent's Putextra method to place additional information, the method checks that the default bundle instance is not empty, if it is empty, creates a new bundle instance, and then puts the specific parameter information into the bundle instance. We can also create the bundle object ourselves, and then specify the 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", 0); Bundle.putstring ("name", "Scott"); Intent.putextras (bundle); StartActivity (intent); }
It is important to note that after the bundle object is set using the Putextras method, the system does not refer to the operation, but rather the copy operation, so if the data in the bundle instance is changed after Setup, the additional information inside the intent will not be affected. So how do we get additional information set in intent? In response, we are going to get the bundle instance from intent and then remove the corresponding key value information from it:
Bundle bundle = Intent.getextras (); int id = bundle.getint ("id");
Of course we can also use intent's Getintextra and Getstringextra methods to get the data source is an instance object of bundle type in intent.
3.category, the trait or behavior of the target to perform the action is categorized
For example: In our application main interface activity usually has the following configuration:
<category android:name= "Android.intent.category.LAUNCHER"/>
The activity on behalf of the target is the initial activity in the task in which the application is located and appears in the list of Apps launcher the system.
A few common category are as follows:
Constant |
Explain |
Category_default |
The default category |
Category_browsable |
Once you have specified this category, when you click on a picture or link on a webpage, you will be considered to include this target activity in an optional list for the user to select to open the picture or link. |
Category_gadget |
The activity can be embedded inside of another activity, that hosts gadgets. |
Category_home |
The activity displays the home screen and the first screen of the user sees when the device was turned on or when the home key is Pressed. |
Category_launcher |
The activity can be the initial activity of a task and was listed in the top-level Application launcher. |
Category_preference |
Indicates that the target activity is a preference interface; |
When you set the 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 declared the category.
Here's an example that goes back to the home screen :
Main.xml:
<?xml version= "1.0" encoding= "Utf-8"?> <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/button1 " Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "go to Home Interface" /> </LinearLayout>
Strings.xml:
<?xml version= "1.0" encoding= "Utf-8"?> <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.button1); Btn.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) { Intent Intent = new Intent (); Intent.setaction (Intent.action_main);//Add ACTION property Intent.addcategory (intent.category_h OME);//Add Category attribute StartActivity (intent);//Start Activity}}); } }
As follows:
Home:
4.type: MIME data type to be processed by the target activity to perform the action
For example, a target activity that can handle a picture contains such a mimetype in its declaration:
When using intent for matching, we can use Settype (string type) or Setdataandtype (Uri data, String type) to set the mimetype.
5.component, the package or class name of the target component
When using component for matching, the following forms are generally used:
Intent.setcomponent (New ComponentName (Getapplicationcontext (), Targetactivity.class)); Intent.setcomponent (New ComponentName (Getapplicationcontext (), "com.scott.intent.TargetActivity"));
The first two are used to match the target within the same package, and the third is to match the target within the other package.
"Note": If we specify the component attribute in intent, the system will no longer match the action, Data/type, category.
Five, Intent usage example Comprehensive summary:
1. Calling the dialer
To mobile customer service 10086 call the URI uri = Uri.parse ("tel:10086"), Intent Intent = new Intent (intent.action_dial, URI); StartActivity ( Intent);
2. Send SMS or MMS
Give 10086 sms URI uri = uri.parse ("smsto:10086") to send content as "Hello"; Intent Intent = new Intent (intent.action_sendto, URI); Intent.putextra ("Sms_body", "Hello"); StartActivity (intent);
Send MMS (equivalent to send SMS with attachments) Intent Intent = new Intent (intent.action_send); Intent.putextra ("Sms_body", "Hello"); Uri uri = uri.parse ("Content://media/external/images/media/23"); Intent.putextra (Intent.extra_stream, URI); Intent.settype ("Image/png"); StartActivity (intent);
3. Open Web page via browser
Open the Google page URI uri = uri.parse ("http://www.google.com"), Intent Intent = new Intent (Intent.action_view, URI); StartActivity (Intent);
4. Send an email
Send the email URI uri = uri.parse ("Mailto:[email protected]") to [email protected]; Intent Intent = new Intent (Intent.action_sendto, URI); startactivity (intent);
Email "Hello" to [email protected] Intent Intent = new Intent (intent.action_send); Intent.putextra (Intent.extra_ EMAIL, "Someo[email protected]"), Intent.putextra (Intent.extra_subject, "SUBJECT"); Intent.putextra (Intent.extra_ TEXT, "Hello"); Intent.settype ("Text/plain"); StartActivity (intent);
e-Mail Intent intent=new Intent (intent.action_send) to many people; String[] tos = {"[email protected]", "[Email protected]"}; Recipient string[] CCS = {"[email protected]", "[Email protected]"}; CC string[] BCCs = {"[email protected]", "[Email protected]"}; Bcc 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/rfc822"); StartActivity (intent);
5. Show map and path planning
Open Google Maps China Beijing location (latitude 39.9, longitude 116.3) URI uri = Uri.parse ("geo:39.9,116.3"); Intent Intent = new Intent (intent.action_view , URI); startactivity (intent);
Path planning: From Somewhere in Beijing (latitude 39.9, longitude 116.3) to a place in Shanghai (north latitude 31.2, longitude 121.4) URI uri = Uri.parse ("http://maps.google.com/maps?f=d&saddr= 39.9 116.3&daddr=31.2 121.4 "); 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.mp3"); Intent.setdataandtype (URI, "Audio/mp3"); StartActivity (intent); Uri uri = Uri.withappendedpath (MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1"), Intent Intent = new Intent ( Intent.action_view, URI); startactivity (Intent);
7. Taking pictures
Open the camera program Intent intent = new Intent (mediastore.action_image_capture); Startactivityforresult (intent, 0);
Take out the photo data bundle extras = Intent.getextras (); Bitmap Bitmap = (Bitmap) extras.get ("Data");
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", 1); The width-to-height ratio of the cut is 1:2intent.putextra ("Aspecty", 2), Intent.putextra ("Outputx", 20); Save the width and height of the picture ("Outputy", Intent.putextra), Intent.putextra ("Output", Uri.fromfile (New File ("/mnt/sdcard/temp")); Save path Intent.putextra ("OutputFormat", "JPEG");//return format Startactivityforresult (intent, 0);
Cut a specific picture 1 Intent Intent = new Intent ("Com.android.camera.action.CROP"); 2 Intent.setclassname ("Com.android.camera", "com.android.camera.CropImage"); 3 Intent.setdata (Uri.fromfile ("New File") ("/mnt/sdcard/temp")); 4 Intent.putextra ("Outputx", 1); The width-to-height ratio of the cut is 1:2 5 Intent.putextra ("Outputy", 2); 6 Intent.putextra ("Aspectx", 20); Save the width and height of the picture 7 Intent.putextra ("Aspecty", 40); 8 Intent.putextra ("scale", true); 9 Intent.putextra ("Nofacedetection", True), Intent.putextra ("Output", Uri.parse ("file:///mnt/sdcard/temp")); 11 Startactivityforresult (Intent, 0);
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 (Int Ent. Action_view, URI); startactivity (intent);
10. Install and Uninstall the program
Uri uri = uri.fromparts ("package", "Com.demo.app", null), Intent Intent = new Intent (Intent.action_delete, URI); StartActivity (Intent);
11. Enter the Settings screen
Enter the wireless network Setup interface (other can extrapolate) Intent Intent = new Intent (Android.provider.Settings.ACTION_WIRELESS_SETTINGS); Startactivityforresult (Intent, 0);
Android summary of--intent mechanism and example summary