An introduction to Android's zero-single-row development diary (11) The intent mechanism of--android

Source: Internet
Author: User

Go on with our Android path. Today I would like to introduce the Android intent.

For component-based application development, not only need to construct and look for components that meet the requirements, more importantly, to connect the components organically, interconnected exchange of information, can ultimately provide the services the application expects. In order to be able to better implement component reuse and make full use of the capabilities of each component, the patterns needed to connect these components are flexible and uniform, and can be dynamically scaled. So Android provides a pattern for building connections and communicating components using intent objects. The intent object is the core of the Android component connection, which embodies the design idea of the whole component Connection model.

First, Intent Object

The core design idea of Android's intent mechanism is the introduction of component management Services as the manager of the connecting component. The service can understand the categories and functions of each component in the system through the configuration information of the component, thus helping the calling component to find the implementation component that meets its requirements, and completely decouple the caller from the provider.

General intent implementation of the flowchart:

  1. The composition of the intent object
    These functions of the intent object are embodied by its realization and design. From the data structure, the implementation of the intent class is very simple, it does not contain complex logic functions, but contains a number of data items.
    (1) Action items are used in intent to represent actions and can be manipulated by intent setaction and Getaction. There are many standard actions defined in Android, such as: Intent.action_view, etc. These actions stipulate the communication specifications between the Android components, ensuring the scalability of the component system.
    (2) Data entry, when a request is initiated, the calling component, if there is an explicit data object, is typically used to store the representation with the datasource. The data is also stored in a string, and its format conforms to the URI standard. So you can use URIs to describe data to enhance the scope of your data.
    (3) Type entry, type is a string data in the mine format that describes the type of request the component can handle, or a type that describes the data, which can represent the entire category of information through a wildcard *. Note: Data entries and type entries are often mutually exclusive, and when Intent.settype is called, the previously set data information is emptied and vice versa. But it can be set at the same time by Intent.setdataandtype ().
    (4) The category category indicates constraints. Each intent object can contain more than one Categroy item. A component needs to support all of the category before it can process requests. If a component needs to start another application and wants to enter the portal component of the application, you need to add Intent.category_launcher as a constraint.
    (5) Component item it refers to the type information of the target component, which can be set by using the Intent.setcomponent method with the class name, or by using the Intent.setclass method to make use of the type object information.
    (6) The carrier of the data transfer in extras intent, which is responsible for passing data from the calling component to the implementation component.
    (7) The flags flags are an integer type, which is compiled from a series of flags.
    In component development, you should follow the relevant specifications developed by the SDK or third parties. When a component needs to support a specific action, it needs to support related extras items and data item related content. The integrity and correctness of the Protocol is the foundation of the entire Android intent mechanism.
  2. Parsing of Intent objects
    From the implementation of component selection, intent objects can be divided into two categories: the exact description of the intent and the intent of the fuzzy description.
    (1) The exact description of the intent refers to all intent objects with component information, and the calling component can be set by means of intent.setcomponent or intent.setclass. When the component Management Service receives the intent object, it verifies its component data item, and if it contains component information, the component Management Service only needs to construct the corresponding implementation component according to component. Usually we use the intent of the jump are used accurate intent.
    (2) In addition, all intent objects that do not contain component information are categorized in the intent of the fuzzy description.

Second, Intent Filter object
In addition to the Intent object, there is an important role in the Android Intent mechanism: the Intent Filter object. The Intent filter object, which refers to the object of the Android.content.IntentFilter class, is the "sister object" of the Intent object. Like the Intent object, the Intent filter object also contains data items such as action, Type, data, catagory, and the structure and meaning of each data item, as well as the Intent data item.

  1. Use of Intent filter
    Intent filter is used by various components to describe its functionality, and with the Intent filter information of the components, Android's component management applications can understand and master the capabilities and requests that each component has. When the component management Service receives a fuzzy-descriptive intent object sent by the calling component, it matches the intent filter information of all components to find the implementation component that meets the requirements.
    Each component can have any number of intent Filter. The more intent Filter objects A component contains, the greater the scope of the intent request that he can accept, and the more complex its implementation will be.
  2. Example of Intent filter
             <ActivityAndroid:name= "Com.example.activitydemo.SecondActivity"> <intent-filter Android:icon=""Android:label=""android:priority="">                 <ActionAndroid:name=""></Action>                 <categoryAndroid:name=""></category>                 <DataAndroid:host=""Android:mimetype=""Android:path=""Android:pathpattern=""Android:port=""Android:scheme=""/>                 <!--you can continue to add the relevant actio, category, and data entries -             </Intent-filter><!--you can continue to add related intent-filter items -                      </Activity>

Three, Intent matching algorithm

When the component Management Service accepts the intent object of the requesting component, it first checks to see if the intent object contains component information for the target implementation component. If not included, the intent filter information for all components is obtained from the app Management Service and is compared to the intent object to select the implementation component that meets the requirements. It involves the matching algorithm of intent.

The algorithm inputs the intent object and the intent filter object for the comparison, and if the return value is positive, the match succeeds, and the greater the value means the higher the match, the flowchart below.


The data and type information is the most complex item in intent filter, and its comparison algorithm is the key to determine the degree of matching between intent and intent filter object.

If the intent object contains type information, it must require the type information of the intent filter to correspond to it, otherwise the match will fail, and if the intent object contains a data item, The URI information of the data item is split into the scheme and authority parts, and the corresponding part of the intent filter object is compared to each other, so that if there is any discrepancy between the two, the match will fail.

As an example of Android native mail application, it configures the following intent filter information:

          <ActivityAndroid:name=". Secondactivity.messagecompose ">             <Intent-filter>                 <ActionAndroid:name= "Android.intent.action.VIEW" />                 <ActionAndroid:name= "Android.intent.action.SENDTO" />                 <DataAndroid:scheme= "mailto"/>                 <categoryAndroid:name= "Android.intent.category.DEFAULT"/>                 <categoryAndroid:name= "Android.intent.category.BROWSABLE"/>                 <!--you can continue to add the relevant actio, category, and data entries -             </Intent-filter>             <!--you can continue to add related intent-filter items -                      </Activity>

An intent match is triggered when the caller makes the following request:

                New Intent (intent.action_sendto);                "" );                 // among them, mailto this part is the scheme part                of the URI Intent.setdata (Uri.parse ("Mailto:[email protected]");                StartActivity (intent);

start the match check. The action contains ok->data contains a ok->category check (a request is made through the context.startactivity function, which is automatically added to the Component Management Service Intent.category_ DEFAULT) ok-> match succeeded .

Iv. Selection of matching components

If more than one intent filter object matches the intent object emitted by the calling component, it needs to be filtered in all eligible intent filter objects to select the implementation component that best meets the calling component and user requirements, which is the choice of the matching component. And we can set the priority of the intent filter object to be set, that is, by changing the Android:priority property in the <intent-filter> configuration item, or dynamically modified by the Intentfilter.setpriority function. The range is 1000 to 1000, and the default is 0.

In the intent mechanism of Android, by introducing the third-party component management Service, the coupling between the calling component and the implementing component is reduced, the flexibility of the whole system and the reusability of the components are improved, which makes the application development easier and quicker. But at the same time, it is because third-party service interventions increase the cost of inter-component connectivity, which can make calls between components less fluid. Therefore, in the component Management Service, the system optimizes the component matching and selection process to improve the efficiency of component invocation, including:

(1) Index
The Component Management Service indexes data items such as action, type, and so on for all intent filter objects through a hash table. Each index entry corresponds to a set of intent filter objects that have the same action, the same type, or other data items. Intent a intent filter object that may match the intent quickly by comparing it with the index entry. In this way, the matching speed is speeded up.

(2) Cache
The so-called cache, is the intent and intent filter matching results recorded, when again encountered the same intent call, you can directly return the results of the last record, thus skipping the matching process, speed up the component calls.

V. A small example of the use of intent

  1. a Activitydemo project that initiates activity for other applications. Where the code is

     Public classChangeactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Button Button=(Button) Findviewbyid (R.id.button); Button Button2=(Button) Findviewbyid (R.id.button2); Button.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {Intent Intent=NewIntent (); //because it's the exact start-up, these don't all have problems.//intent.addcategory (Intent.category_launcher); //intent.setaction (intent.action_main);ComponentName cn =NewComponentName ("Com.example.demo",//Another app's package name"Com.example.demo.MainActivity");//the class name of another app to start//intent.setflags (intent.flag_activity_new_task);Intent.setcomponent (CN); LOG.D ("TEST", intent.tostring ());                StartActivity (Intent); //another way to start exactly                /*Intent launchintent = Getpackagemanager (). Getlaunchintentforpackage ("Com.example.demo");                LOG.D ("TEST", launchintent.tostring ()); StartActivity (launchintent);*/            }        }); Button2.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//only System-level application components are available//action is main, application portal interfaceIntent Intent =NewIntent (Intent.action_main);                Intent.addcategory (Intent.category_launcher);                                StartActivity (Intent); //get all compliant components, including third-party installed apps//list<resolveinfo> activities = Getpackagemanager (). Queryintentactivities (Intent, Packagemanager.match_                DEFAULT_ONLY); //Customize dialog box//Showselectactivitydialog (activities);            }        }); }}

  2. Another application, which is the package named Com.example.demo, where the configuration file section is:

    <ActivityAndroid:name= "Com.example.demo.MainActivity"Android:label= "@string/app_name" >            <Intent-filter>                <ActionAndroid:name= "Android.intent.action.MAIN" />                <categoryAndroid:name= "Android.intent.category.LAUNCHER" />            </Intent-filter>        </Activity>
  3. Install the above two applications and run:

    Click on the exact intent to jump to another app.
    Click the blur intent, and a list of component selections appears, such as:

PS: One of the detailed usage of Packagemanager, can refer to this article Android essay-packagemanager detailed

Vi. concluding remarks

See here, we are not the intent of the transmission principle of some understanding of it. Image point, intent is a plug, and intent filter is like a socket, socket hole as long as the number of holes to meet the plug can work, more than nothing, but less can not.

Intent is the core of Android application model, which solves the problem of connectivity between components. The intent matching strategy provided by the component Management Service reduces the coupling between components, improves the flexibility of the platform, enhances the reusability of the components, and radically reduces the burden of application development.

Reference article: (1) Android intent mechanism detailed http://www.oschina.net/question/565065_67909

(2)Android Intent and intent action Daquan http://www.apkbus.com/android-72361-1-1.html

========================================

Cpacm

Address: http://www.cnblogs.com/cpacm/p/3939937.html

An introduction to Android's zero-single-row development diary (11) The intent mechanism of--android

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.