Android component communication-Intent

Source: Internet
Author: User
Tags home screen

1. Overview

One applicationProgramThree core components --Activities,Services,Broadcast ReceiversAll are activated through messages called intents. Intent messages are a mechanism for delayed runtime binding between components in the same or different applications. Intent itself (IntentObject) is a passive data structure that stores an abstract description of the operation to be executed, or in the case of broadcast, it is usually that something has occurred and is being declared. The three components have an independent intent transfer mechanism:

    • Activity: An intent object is passedContext. startactivity ()OrActivity. startactivityforrestult ()Start an activity or make an existing activity to do new things.
    • Service: An intent object is passedContext. startservice ()Initialize a service or pass a new command to the running service. Similarly, an intent can be passedContext. bindservice ()Create a connection between the calling component and the target service.
    • Broadcast receiver er: An intent object is passed to any broadcast method (suchContext. sendbroadcast (),Context. sendorderedbroadcast (),Context. sendstickybroadcast ()), Will be passed to all interested broadcast recipients.

In each case, the android system finds the appropriate activity, service, and broadcast receivers to respond to the intent. If necessary, initialize them. There is no overlap between these message systems, that is, the broadcast intent will only be passed to the broadcast receiver, instead of the activity or service, and vice versa.

Next we will first describe the intent object, and then introduce the rule for Android to map intent to the corresponding component-how to solve which component should receive intent messages. For intent with no target component name specified, this process includes matching each potential target object according to intent filters.

2. Intent object

An intent object is a bundle of information that contains information about components that are interested in intent (for example, actions to be executed and data to be applied) information of interest to the Android system (such as the classification information for processing intent components and instructions on how to start the target activity ). The following lists its main information:

2.1 component name

Name of the component that processes intent. This field isComponentnameObject -- is the fully qualified class name of the target component (for example, "com. example. project. app. freneticactivity ") and the name of the package where the application is located in the list file (for example," com. example. project. The package in the component name does not have to be the same as the package name in the configuration file.

The component name is optional. If it is set, the intent object is passed to the instance of the specified class. If it is not set, android uses other information in intent to locate the appropriate target component (see intent resolution below ). The component name isSetcomponent (),Setclass ()OrSetclassname ()SetGetcomponent ()Read.

2.2 Action

An action named after a string will be executed, or an action has occurred in broadcast intent and is being reported. The intent class defines some action constants as follows:


Target component




Initiate a phone call.



Display data for the user to edit.



Start up as the initial activity of a task, with no data input and no returned output.



Synchronize data on a server with data on the mobile device.


Broadcast receiver er

A warning that the battery is low.


Broadcast receiver er

A headset has been plugged into the device, or unplugged from it.


Broadcast receiver er

The screen has been turned on.


Broadcast receiver er

The setting for the time zone has changed.

For more actions, see intent class. Other actions are defined in the android API. We can also define our own action strings to activate components in our applications. The Custom Action string should contain the application registration prefix, such as "com. example. Project. show_color ".

The action largely determines how the remaining intent is built, especially the data and extras fields, just as a method name determines the parameters and return values. For this reason, specify the action as clearly as possible and closely associate it with other intent fields. In other words, you should define the entire Protocol of the intent object that your component can process, instead of simply defining an action separately.

The action of an intent object passes throughSetaction ()Method settings, throughGetaction ()Method.

2.3. Data

Data is the URI and MIME type that will act on the data on it. Different actions have different data specifications. For example, if the action field is action_edit, the data field will contain the URI of the document to be edited. If the action is action_call, the data field will be a Tel: URI and the number to be called; if the action is action_view and the data field is an http: URI, the receiving activity is called to download and display the data pointed to by the URI.

When an intent is matched to a component that can process data, it is usually known that the data type (its MIME type) and its URI are very important. For example, a component can display image data and should not be called to play an audio file.

In many cases, the data type can be inferred from the URI, especially content: Uris, which indicates the data on the device and is controlled by the content provider. However, the type can also be explicitly set,Setdata ()Method to specify the data Uri,Settype ()MIME type,Setdataandtype ()Specify the URI and MIME types of data. PassGetdata ()Read Uri,GetType ()Read type.

2.4. Type

In addition, it contains information about the component types that should process intent. You can specify any number of types in an intent object. Some Type constants defined by the intent class are as follows:




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.


the activity can be embedded inside of another activity that hosts gadgets.


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.


the activity can be the initial activity of a task and is listed in the top-level application launcher.


the target activity is a preference panel.

For more types of constants, see intent class.

Addcategory ()Method to add a category to the intent object,Removecategory ()Method to delete a previously added category,Getcategories ()Method To obtain all types in the intent object.

2.5 Additional information

The extra key-Value Pair information should be passed to the component to process intent. Just like the data Uris of a specific type associated with an action, it is also associated with certain additional information. For example, an action_timezone_change intent has an additional "time-zone" to identify the new time zone. action_headset_plug has an additional "state" to identify whether the header is full or not; there is a "name" Additional Information that identifies the type of the header. If you customize a show_color action, the color value can be set in the appended key-value pair.

Intent object has a seriesPut... ()This method is used to insert various additional data and a seriesGet... ()Used to read data. These methods are similar to the bundle object method. In fact, additional information can be used as a bundle.Putextras ()AndGetextras ()Install and read.

2.6. Logo

There are a variety of logos, many of which indicate how the Android system starts an activity (for example, the activity should belong to that task) and how to treat it after it starts (for example, whether it belongs to the list of recent activities ). All these flags are defined in the intent class.

3. Intent Parsing

Intent can be divided into two groups:

    • Explicit intent: Specify the target component by name. Because developers generally do not know the component names of other applications, explicit intent is usually used for internal messages of the application, such as starting a subordinate service or starting a sister activity.
    • Implicit intent: The target name is not specified (the component name field is empty ). Implicit intent is often used to activate components in other applications.

Android transmits an explicit intent to an instance of the specified target class. In the intent object, only the component name content is used to determine which component should obtain the intent, instead of other content.

Implicit intent requires a different policy. Because a target is specified by default, the android system must find the most suitable component (some components) to process intent-an activity or service to execute the request action, or a group of broadcast recipients to respond to the broadcast statement. This is done by comparing the content of the intent object and the intent filter (intent filters. Intent filters are associated with potential components that receive intent. Filters declare the capabilities of a component and define intents that it can process. They open the component to receive the declared intent type of implicit intents. If a component does not have any intent filter, it can only receive the displayed intents, and the component that declares the intent filter can receive the displayed and implicit intents.

It is considered only when the following three aspects of an intent object comply with an intent filter: Action, data (including Uri and data type), and category. Additional information and flag do not work in parsing which component receives intent.

3.1 intent Filter

Activity, service, and broadcast receivers can have one or more intent filters to inform the System of the implicit intent values that can be processed. Each filter describes a set of intents that a component is willing to receive. In fact, it filters out the intents that you don't want, and only the implicit intents that you don't want. An explicit intent can always be passed to its target component, no matter what it contains; a filter is ignored. But an implicit intent can only be passed to it through one of the filter components.

Each task that a component can perform has an independent filter. For example, the noteediter activity in Notepad has two filters: one is to start a specified record, which can be viewed and edited by the user, and the other is to start a new and empty record, the user can fill and save.

An intent filter is an instance of the intentfilter class. Because the Android system must know its capabilities before starting a component, but the intent filter is usually not in JavaCodeIn the application configuration file (Androidmanifest. xml)<Intent-filter>Element settings. However, with one exception, the filter of the broadcast receiver is calledContext. registerreceiver ()Dynamic Registration, which directly creates an intentfilter object.

A filter has fields corresponding to the action, data, and type of the intent object. The filter must detect all three fields of the implicit intent. If any of these fields fails, the android system will not pass the intent to the component. However, because one component can have multiple intent filters, one intent cannot detect the filter of the component, and other filters may pass the detection.

3.1.1 action Detection

In the configuration file<Intent-filter>Element<Action>The sub-element lists actions, for example:

 <  Intent - Filter ... >      <  Action   Android : Name = "Com. example. Project. show_current"   />      <  Action  Android : Name = "Com. example. Project. show_recent"   />      <  Action   Android : Name = "Com. example. Project. show_pending"   /> ... </  Intent -Filter > 

As shown in the example, although an intent object is only a single action, more than one filter can be listed. This list cannot be blank. A filter must contain at least one<Action>Child element, otherwise it will block all intents.

To pass the detection, the action specified in the intent object must match one in the action list of the filter. If no action is specified for the object or filter, the result is as follows:

    • If no action is specified for the filter, no intent will match, and all intent will fail to detect, that is, no intent can pass the filter.
    • If no action is specified for the intent object, it will pass the check automatically (as long as the filter has at least one filter, otherwise it will be the case above)
3.1.2. Category Detection

Similarly, in the configuration file<Intent-filter>Element<Category>The sub-element lists the types, for example:

    intent - filter ... >    Category   Android :  name  = " android. intent. category. default " />     Category   Android :  name  = " android. intent. category. browsable " /> ...    intent -filter > 

Note that the actions and type constants listed in the previous two tables in this article are not used in the list file, but use the full string value. For example, the "android. Intent. Category. browsable" string shown in the example corresponds to the browsable constant mentioned above. Similarly, the "android. Intent. Action. Edit" string corresponds to the action_edit constant.

For an intent to pass the kind detection, each kind in the intent object must match one of the filters. That is, the filter can list additional types, but the types in the intent object must be found in the filter. Only one type is not in the filter list, even if the type detection fails!

Therefore, in principle, if an intent object does not have a category (that is, the Type field is null), it should always pass the type test, regardless of the category in the filter. However, Android treats allContext. startactivity ()It seems that they contain at least "android. Intent. Category. Default" (corresponding to the category_default constant ). Therefore, to receive an implicit intent, the activity must include "android. Intent. Category. Default" in the intent filter ".

Note: "android. Intent. Action. Main" and "android. Intent. Category. launcher" are set to mark new tasks started by the activity and bring them to the startup list. They can include "android. Intent. Category. Default" to the category list or not.

3.1.3 Data Detection

Similarly, in the configuration file<Intent-filter>Element<DATA>Sub-elements list data, for example:

 <  Intent - Filter ... >      <  Data   Android : Mimetype = "Video/MPEG"   Android : Scheme = "HTTP" .../>       <  Data   Android : Mimetype = "Audio/MPEG"   Android : Scheme = "HTTP" ... /> ... </  Intent -Filter > 

Each<DATA>The element specifies a URI and data type (MIME type ). It has four attributesScheme,Host,Port,PathCorresponds to each part of the URI:
Scheme: // host: Port/path
For example, the following URI:
Content: // com. example. Project: 200/folder/subfolder/etc
Scheme is content, host is "com. example. Project", port is 200, and path is "folder/subfolder/etc ". The host and port form the URI credenity (Authority). If the host is not specified, the port is ignored.
These four attributes are optional, but they are not completely independent. To make authority meaningful, scheme must also be specified. To make the path meaningful, both scheme and authority must be specified.

When comparing the intent object and the filter Uri, only the URI attribute in the filter is compared. For example, if a filter only specifies scheme, all URLs with this scheme match the filter. If a filter specifies scheme and authority, but does not specify path, all URLs that match scheme and authority are detected, regardless of their path. If all four attributes are specified, matching is required for matching. However, the path in the filter can contain wildcards to match part of the path.

<DATA>ElementTypeAttribute specifies the MIME type of the data. Intent objects and filters can both use the "*" wildcard to match child type fields, such as "text/*" and "audio/*" to represent any child type.

Data Detection must detect both the URI and the data type. The rules are as follows:

    • An intent object neither contains the URI nor the Data Type: it cannot pass the detection only when the filter does not specify any Uris and data type; otherwise, it can pass.
    • An intent object contains a URI but does not contain a data type. Only when the filter does not specify a data type and their URI matches can the object be detected. For example,Mailto:AndTel:No actual data is specified.
    • An intent object contains a data type, but does not contain a URI: it is detected only when filtering contains only the data type and is the same as intent.
    • An intent object contains both the URI and the data type (or the data type can be inferred from the URI): the data type part is passed only when it matches one of the filters; The URI part, its URI will appear in the filter, or it hasContent:OrFile:Uri, or the filter does not specify the URI. In other words, if its filter only lists the data type, the component assumes thatContent:AndFile:.

If an intent can pass more than one activity or service filter, the user may be asked that the component is activated. If no target is found, an exception occurs.

3.2 General situation

The last rule above indicates that the component can obtain local data from a file or content provider. Therefore, their filters only list data types and do not need to be explicitly specifiedContent:AndFile:The name of scheme. This is a typical case.<DATA>The elements are as follows:

<Data Android:Mimetype="Image /*" />

Tells android that the component can obtain image data from the content provider and display it. Because most of the available data is distributed by the content provider, the filter specifies a data type but does not specify the URI, which may be the most common.

Another common configuration is that the filter specifies a scheme and a data type. For example<DATA>The elements are as follows:

<Data Android:Scheme="HTTP" Android:Type="Video /*" />

Tells android that this component can obtain video data from the network and display it. When a user clicks a link on a web page, what will the browser application do? First, it will try to display data (if link is an HTML page, it will be displayed ). If it cannot display data, it adds an implicit intent to scheme and the data type to start an activity that can do this. If there is no receiver, it will request the Download Manager to download the data. This will be done under the control of the content provider, so a potential large activity pool (their filters only have data types) can respond.

Most applications can start new activities without referencing any special data. The activity has a filter for the action specified by "android. Intent. Action. Main" to start the application. If they appear in the application launch list, they also specify the "android. Intent. Category. launcher" type:

<Intent-Filter...><Action Android:Name="Code Android. Intent. Action. Main" /><Category Android:Name="Code Android. Intent. Category. launcher" /></Intent-Filter>
3.3 Use intent match

Intents matches the intent filter to discover not only a target component to activate, but also other information about the component on the device. For example, the android system fills in the application startup list and displays the applications that can be started by users on the screen at the highest level. intent. action. main and Android. intent. category. launcher "Type filters, and then the icons and labels of these activities are displayed in the launch list. Similarly, it finds the main menu of activity discovery with the "android. Intent. Category. Home" filter.

Our applications can also use this intent matching method. Packagemanager has a groupQuery... ()Method returns all the components that can receive a specific intent, a groupResolve... ()The method determines the most appropriate component response intent. For example,Queryintentactivities ()Returns a group of all activities that can execute the specified intent parameter, similarQueryintentservices ()Returns a group of services. Both methods do not activate components. They only list all components that can respond. There are similar methods for the corresponding broadcast Receiver --Querybroadcastreceivers ().











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: 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.