Intent mechanism in Android

Source: Internet
Author: User

1. OverviewThe three core components of an application, activities, services, and broadcast receivers, are all activated through messages called intents. Intent messages are a mechanism for delayed runtime binding between components in the same or different applications. Intent itself is an Intent object). It 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 passed to Context. startActivity () or Activity. startActivityForRestult () to start an Activity or make an existing Activity to do new things.
·Service: An intent object is passed to Context. startService () to initialize a service or send a new command to a running service. Similarly, an intent can be passed to Context. bindService () to establish a connection between the calling component and the target service.
· Broadcast Receiver: an intent object is passed to any Broadcast method, such as Context. 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 broadcastreceivers 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 objectAn Intent object is a bundle of information that contains information about components that are interested in intent, such as the actions to be executed and the data to be applied) information of interest to the Android system, such as classification information for processing intent components and instructions for Starting target activities ). The following lists its main information: (1) component nameName of the component that processes intent. This field is a ComponentName object -- it is a fully qualified class name of the target component, such as "com. example. project. app. freneticActivity) and the package of the application in the list file, such as "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. For more information, see the Intent resolution below ). The component name is set by setComponent (), setClass (), or setClassName () and read by getComponent.
(2) ActionAn 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:

Constant -- Target component -- Action

ACTION_CALL -- activity -- Initiate a phone call. Initiate a phone call.

ACTION_EDIT -- activity -- Display data for the user to edit.

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

ACTION_SYNC -- activity -- Synchronize data on a server with data on the mobile device.

ACTION_BATTERY_LOW -- broadcast receiver er -- A warning that the battery is low.

ACTION_HEADSET_PLUG -- broadcast receiver er -- A headset has been plugged into the device, or unplugged from it.

ACTION_SCREEN_ON -- broadcast receiver er -- The screen has been turned on.

ACTION_TIMEZONE_CHANGED -- broadcast receiver -- 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 data) and the extras field is appended, just like 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 is set by the setAction () method and read by the getAction () method. (3) dataData) 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, the MIME type of the data is usually known) and its URI is 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 set explicitly. The setData () method specifies the data URI, setType () specifies the MIME type, and setDataAndType () specifies the data URI and MIME type. Use getData () to read URI and getType. (4) TypesIn 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:

Constant -- Meaning

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

CATEGORY_GADGET -- The activity can be embedded inside of another activity that hosts gadgets.

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

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

CATEGORY_PREFERENCE -- The target activity is a preference panel.

For more types of constants, see Intent class. AddCategory () method adds a category to the Intent object. The removeCategory () method deletes a previously added category. The getCategories () method gets all types in the Intent object. (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_CHANGEintent 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 objects have a series of put... () Method is used to insert various additional data and a series of get... () Is used to read data. These methods are similar to the Bundle object method. In fact, additional information can be installed and read as a Bundle using putExtras () and getExtras. (6) FlagThere 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 is started, for example, whether it belongs to the latest activity list ). All these flags are defined in the Intent class. 3. Intent ParsingIntent 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 component name field that does not specify the target name is blank ). 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 a component that is most suitable for some components) to process intent-an activity or service to execute the request action, or a group of broadcast receivers to respond to the broadcast declaration. This is done by comparing the content of the Intent object and the intent filter intentfilters. 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.

Only when the following three aspects of an Intent object comply with an intent filter: action, data including URI and data type) and category are considered. Additional information and flag do not work in parsing which component receives intent. (1) Intent FilterActivity, 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. The Android system must know its capabilities before starting a component, but the intent filter is usually not set in java code, but in the AndroidManifest file of the application. in xml) with the <intent-filter> element. With one exception, the filter of the broadcast receiver dynamically registers by calling Context. registerReceiver (), 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. (1.1) Action DetectionThe <intent-filter> element in the configuration file lists actions with <action> child elements, for example:
 
 
  1. <intent-filter . . . > 
  2.    <action android:name="com.example.project.SHOW_CURRENT" /> 
  3.    <action android:name="com.example.project.SHOW_RECENT" /> 
  4.    <action android:name="com.example.project.SHOW_PENDING" /> 
  5.    .. . 
  6. /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> sub-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 automatically pass the check as long as there is at least one filter in the filter, otherwise it will be the case above) (1.2) type detectionSimilarly, the <intent-filter> element in the configuration file lists the types with <category> sub-elements, for example:
 
 
  1.  <intent-filter . . . > 
  2.     <category android:name="android.intent.category.DEFAULT" /> 
  3.     <category android:name="android.intent.category.BROWSABLE" /> 
  4.     .. . 
  5. </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 type of the filter. However, with an exception, Android treats all the implicit intents passed to Context. startActivity () as if they contain at least the "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.

(1.3) Data Detection

Similarly, the <intent-filter> element in the configuration file lists data with <data> child elements, for example:
 
 
  1.  <intent-filter . . . > 
  2.     <data android:mimeType="video/mpeg" android:scheme="http" . . . /> 
  3.     <data android:mimeType="audio/mpeg" android:scheme="http" . . . /> 
  4.     . . . 
  5. </intent-filter> 

Each <data> element specifies a URI and a data-type MIME type ). It has four attributes: scheme, host, port, and path, which correspond 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 credential authority of the URI together. 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> the type attribute of the element 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 or 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: And tel: do not specify the actual data.
· An Intent object contains a data type, but does not contain a URI: it passes detection 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 data type that 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 should appear in the filter, or it has content: or file: URI, or the filter does not specify the URI. In other words, if its filter only lists data types, the component assumes that it supports content: and file :.

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. (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 explicitly specify the names of content: and file: scheme. This is a typical case. A <data> element is like the following:

 
 
  1. <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, an <data> element is like the following:
 
 
  1. <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 has only data types in their filters) 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:
 
 
  1.  <intent-filter . . . > 
  2.     <action android:name="codeandroid.intent.action.MAIN" />    <category android:name="codeandroid.intent.category.LAUNCHER" /> 
  3. </intent-filter> 
(3) Use intent to matchIntents 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 through the activity that contains the "android. intent. category. HOME" filter. Our application can use this Intent matching method similarly. PackageManager has a set of queries... () Method returns all the components that can receive a specific intent, a set of resolve... () Method determines the most appropriate component response intent. For example, queryIntentActivities () returns a group of services that can be used to execute all the activities of the specified intent parameter. Similar queryIntentServices () returns a group of services. Both methods do not activate components. They only list all components that can respond. The corresponding broadcast receiver has a similar method: 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: 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.