In-depth understanding of intent and Intentfiler (i)

Source: Internet
Author: User

http://blog.csdn.net/u012637501/article/details/41080891

For a more profound understanding and flexible use of intent, I plan to divide this part of the study into two steps: one is to understand the basic concepts of intent and its classes, and to illustrate the flexibility of using intent to start a component and to implement data transfer between components. What is intent and what is the role?Android applications include four components: Activity, ContentProvider, Service, Broadcastreceiver, and in order to facilitate communication between different components, the application uses a unified way to launch components and pass data                , that is, using intent. Intent encapsulates the "intent" of an Android application to start a component, and the object of the intent class is a communication vector between components, and a intent object is a set of information that contains information that is of interest to receive intent components, such as action and data) and information about the Android system (such as category, etc.). That is, the component that sends the "intent" launches the specified (that is, the component property) or some component of the filter (that is, the Action&category property) through the content contained in the intent object. The corresponding action is then implemented (that is, the Action property) and the corresponding data (that is, the Data property) is passed in order to complete the corresponding action.

Intent is how to implement inter-component calls?

1.Intent implementationsRequest a simple implementation flowchart of an activity component, which is the most used intent parsing instance. First, the component that emits "intent" starts the component by calling Context.startactivity (intent): The component that emits the "intent" passes in the already-well-intent object (a set of information that determines whether another component can be successfully started); The action "actually executes the instrumentation object, which is the activity manager that activates the entire application, centrally responsible for all activity within the application." It has a hidden method execstartactivity method, which is responsible for initiating activity according to intent.   The method removes some of the details, and the most important thing it does is to pass this call, via RPC, to the Activitymanagerservice. Finally, Activitymanagerservice will submit these critical information to another service Packagemanagerservice, which will have information about the entire package and its components, which would pass the intent, with all known intent Filters to match (if you have component information, you don't have to.) If found, the relevant component information back to Acitivitymanagerservice, here, will be done to start the activity of the many details of the matter. 2.Intent MatchingHow do the components that make "intent" come up with the required components? Here, Intent Filters began to work, Intent Filters defined in the Androidmainfest.xml file, each activity will have a <intent filters/> element, it contains a <action/>, <data/> and other sub-elements. When our intent object does not contain component information, this "intent" is called stealth "intent". In other words, "intent" does not specify which component to start and what action to complete. At this point we need to match the information with the child elements in the intent filters to determine whether the activity that currently contains the intent filters attribute is the component that we want to start. That is, the send "intent" component configures the Intent object, the Intent Filters property is implemented by the initiating component, and finally, the sending component is based on the <intent filters/> in the androidmainfest.xml of the boot component Information to determine if it is a target component.

Three, intent object detailed

The object of intent class is the communication carrier between components, and we can easily realize the communication between different components by using intent object. A Intent object is a set of information that is embodied in the 7 attributes of its component, Action, Category, Data, Extra, and flag. Intent represents the startup "intent" of Android apps, and the Android app will launch the specified component according to intent, as to which component to start, depending on the properties of the intent. 1.Action PropertiesThe Action property is a normal string that represents what kind of "action" the intent object is going to accomplish. When we specify an action for the intent object, the component that is launched will behave in accordance with the instructions of the action, such as viewing, dialing, editing, etc. it is important to note that a component, such as activity, can have only one action. We can facilitate communication between our own application components, customize the action's (string) to create new actions, or you can directly use static member variables in the intent class, such as Action_view,action_pick, They are a batch of action variables that are predefined for the Action property in Android. There are two ways to set the intent object Action property: [Java]View PlainCopyprint?
  1. (1) Custom string
  2. Public final String custome_action="Intent.action.CUSTOME_JIANG"; Strings can be arbitrarily
  3. Intent intent=New Intent ();
  4. Intent.setaction (actionattr.custome_action); //Note: Actionattr is a class that we create, and you can also use this. Custome_action
  5. (2) using the system to schedule an action constant
  6. Intent intent=New Intent ();
  7. Intent.setaction (Intent.action_call); //Where Action_call is a static member variable of the intent class and can be called directly by class
  8. //corresponding string "Android.intent.action.CALL"
2.Data PropertiesThe Action property describes an "action" for the intent object, and the Data property provides the operation's information for the intent object's Action property. Note here that the Data property accepts only one Uri object, and a URI object is typically represented by a string of the following form: URI string format: scheme://host:port/path Example: content:// COM.ANDROID.CONTACTS/CONTACTS/1 or tel://18819463209 can do this when setting the intent object's Data property: [Java]View PlainCopyprint?
    1. Intent intent=New Intent ();
    2. String data="CONTENT://COM.ANDROID.CONTACTS/CONTACTS/1";
    3. Uri uri=uri.parse (data); //Convert a string to a URI
    4. Intent.setdata (URI);
    5. Or
    6. Intent intent=New Intent ();
    7. Intent.setdata (Uri.parse ("CONTENT://COM.ANDROID.CONTACTS/CONTACTS/1"));
Blogger notes the 1:action attribute and the Data property are the main parts of the information passed by intent, Action/data attribute examples: Action_view CONTENT://CONTACTS/PEOPLE/1--Information passed: Display Information about the person with the number 1 action_dial CONTENT://CONTACTS/PEOPLE/1--Message Sent: Call the person who is numbered 1 Action_view tel:123--Message Sent: Show number 123 Action_ DIAL tel:123--Message Sent: Call number 123action_edit CONTENT://CONTACTS/PEOPLE/1--message: Edit contact with number 1 Action_view content:// contacts/people/--Message passed: Lists show all contacts. If you want to view a contact, you need to define a new intent and set the property to {Action_view content://contacts/n} Passed to a new activity. Summary: The Action property, the Data property, is the primary property of intent. 3.Catagory PropertiesWith the action, the data or type attribute can be used to accurately express a complete intent. But in order to make the "intent" more precise, we also add some constraints to the intent, which is implemented by the Catagory property of "intent". One intent is to specify only one action property, but you can add one or more catagory properties. The Category property allows you to customize the string implementation, but you can also set the system predefined category constants to facilitate communication between different applications. The call method Addcategory is used to add a category to intent, and the method removecategory is used to remove a category;getcategories method to return the defined category. You can do this when you set the intent object Categoty property: [Java]View PlainCopyprint?
    1. (1) Custom string
    2. Public final String custome_category="Intent.action.CUSTOME_CATEGORY"; Strings can be arbitrarily
    3. Intent intent=New Intent ();
    4. Intent.addcategory (actionattr.custome_category);
    5. (2) Use the system to schedule action, category constants
    6. The following code implements the intent object implementation to return to the home desktop when a button is clicked.
    7. Intent intent=New Intent ();
    8. Intent.setaction (Intent.action_main);
    9. Intent.addcategory (Intent.category_home); //Back to home desktop
Blogger Note 2: Generally, both the action and category properties are used together. In Android, all apps are active (that is, the first activity that runs when you start it alone ...) ), it is necessary to be able to accept the intention of a CATEGORY of category_launcher,action as Action_main. For components that emit "intent", we can add the Action property to intent by using the setaction (), Addcategory () method, or add the action, category property at the same time, and for the component that receives the intent, In the Androidmanifest.xm file, we can set:<application        android:allowbackup= "true"         android:icon= "@drawable/ic_launcher"         android:label= "@string/app_name"         android:theme= "@style/apptheme" >        <activity      &NB Sp     android:name= ". Actioncateattr "            android:label=" First activity interface ">        &N Bsp   <intent-filter>                <action android:name= " Android.intent.action.MAIN "/>            //default action          &N BSp     <category android:name= "Android.intent.category.LAUNCHER"/>    //default category             </intent-filter>        </activity>  &nbsp ;          <activity            android:name= ". Secondaryactivity "            android:label=" second activity interface ">            <intent-filter>                <action android:name= "Intent.action.JIANG_ACTION"/>                <category android:name= " Intent.action.JIANG_CATEGORY "/>                <category android: Name= "Android.intent.category.DEFAULT"/>    //default category            </ intent-filter>        </activity> Comments: Hair"Intention" activity will be category Category_launcher,action as Action_main, receive "intention" activity must set a default category attribute Category_default , this cannot be set to Category_launcher no will error. Also, if we use the system's predefined action constants, we need to add the appropriate permissions in the Androidmanifest.xm file, which we'll cover in the second section. 4.Type PropertiesThe Type property is used to specify the MIME type for the URI specified by the data, which can be any custom MIME type, as long as the string conforms to the ABC/XYZ format. It is important to note that the type attribute and the Data property are generally covered by each other, and if you want the intent to have a type attribute with both the Data property, you must do so through the Setdataandtype () method. As for the understanding of the type attribute, I remember that there is a blog post like this: When you say data, you have to mention the type, and many times, someone will misunderstand that the difference between data and type is just like the difference between a girl and a chick. But in fact, the type information is expressed in mime, such as text/plain, such things. Here, the difference between the two is very clear, the data is the house number, indicating the specific location, the specific problem of specific analysis, and type, is to emphasize the feather, to solve a batch of problems. The actual example is this, for example, a call from an application, will be initiated by the action is action_dial and data for tel:xxx such intent, the corresponding human language is to call XXX phone, very elephant. And if you use type, it's a lot wider, like a browser receiving an unknown MIME type of data (such as a video ...). ), it will release such intent, the other system should be used to help, expressed as natural language should be: View PDF documents, such. Bo Master Note 3:mime type?

MIME (Multipurpose Internet Mail Extensions) Multipurpose Internet Mail Extension type is the type of file that is set up with an extension that is opened by an application, and when the extension file is accessed, The browser will automatically open with the specified application. Many are used to specify some client-customized file names, as well as some ways to open media files. In the earliest HTTP protocol, there was no additional data type information, all transmitted data was interpreted by the client as Hypertext Markup Language HTML documents, and in order to support the multimedia data type, the HTTP protocol used the MIME data type information appended to the document to identify the data type. MIME is a multi-functional Internet Mail extension designed to append multimedia data when sending e-mail, allowing mail clients to process according to their type. However, when it is supported by the HTTP protocol, its meaning is even more pronounced. It makes the HTTP transfer not only the ordinary text, but also become colorful. Each MIME type consists of two parts, preceded by a large category of data, such as audio audio, image image, and so on, followed by a specific category.

Common MIME Types (generic): Hypertext Markup Language text. HTML text/htmlxml document. XML text/xmlxhtml document. XHTML application/xhtml+xml Plain text. txt text/ Plainrtf text. rtf application/rtfpdf document. PDF Application/pdfmicrosoft Word file. Word application/mswordpng image. png image/ Pnggif graphics. gif image/gifjpeg graphics. jpeg,.jpg Image/jpegau sound file. Au audio/basicmidi music file Mid,.midi audio/midi,audio/ X-midirealaudio music files. RA,. Ram audio/x-pn-realaudiompeg file. mpg,.mpeg Video/mpegavi file. avi video/x-msvideogzip file. gz Application/x-gziptar file. Tar application/x-tar arbitrary binary data Application/octet-stream 5.Ertras PropertiesThrough these items, the identification of the problem, the basic perfect solution, the remaining one important problem, is the transfer of parameters. Extras is used to do this thing, it is a bundle class object, there is a set of serializable key/value pairs composed. Each action will have a key and value type convention corresponding to it, and when initiating the intent, the additional parameters that data cannot represent will need to be placed in extras as required. 6.Flags Propertiescan identify, there is input, the entire intent basic is complete, but there are some accessories instructions, need to put in the flags in the past. As the name implies, flags is a number of shapes, and there are some column flags that are used to indicate the mode of operation. For example, you expect the executor of this intent, and you to run in two completely different tasks (or the process is no harm ...). ), you need to set the FLAG_ACTIVITY_NEW_TASK flag bit. 7.Component PropertiesIn general, "intent" can be divided into display intent and implicit intent. Intent filters It is used to describe a component such as an activity or serveice, we add <action/in the <intent-ilters/> element in the component Androidmanifest.xml > and other attributes to meet the expectations of how to respond to the intent, this does not indicate the way to start the component name is called implicit intent. Of course, we can also enable the "intent" implementation to launch the specified component, known as the display intent, mainly through the component property. The component property of intent needs to accept a ComponentName object, which binds to the intent of the class name and the package name where the class is to be started. [Java]View PlainCopyprint?
    1. ComponentName comp=New ComponentName (componentattr. This,secondaryactivity.   class);
    2. Intent intent=New Intent ();
    3. Intent.setcomponent (comp); //Set the component property of the intent, specify the package and class name "intent" to start the component
    4. Note: The first sentence is used to create a ComponentName object that specifies the package name and type-which can uniquely determine a component class.
Iv. Intent related Categories 1.Activity classHere we just need to learn how to use intent to start the activity component.
void StartActivity (Intent Intent) Role: Start activity, specifically start which activity and how to boot up by the Intent attribute
void Startactivityforresult (Intent Intent, int requestcode) Acts: Initiates activity and returns a result. When the activated activity exits, it calls the Onactivityresult () method and passes it a requestcode parameter, which is a non-negative requestcode parameter (>0), which is the function of which activity component is issued. Intention ", it should be noted that if Requestcode is less than 0 o'clock, this method can only be used to start an activity and cannot return a value. In addition, the Action property of intent is set to return a result if set to Intent.ACTION_MAIN orIntent.ACTION_VIEW,也是不能获取结果的。
To write: There is also how to start the service, Broadcastreceiver components of the method, this later learned to say it. 2.Intent class(1) Constructors
Intent (): Create an empty constructor Intent (Intent o): copy constructor
Intent (String action): Create an Intent object with the Acion property
Intent (String action, Uri URI): Creates an intent with the Action property to accept a Uri object
Intent (Context packagecontext, class<?> CLS): Creating an intent to have a specified component
Intent (String action, Uri Uri, Context packagecontext, class<?> CLS) creates an intent with an action and data property for a specified component

In-depth understanding of intent and Intentfiler (i)

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.