Study Notes for Android: intent & intent Filter

Source: Internet
Author: User
Tags home screen
Intents And intent Filters

Three core components of the application-activity, service, and broadcast receiver-are activated through messages called intent. Intent messages are used to bind two components in the same or different applications at runtime. An intent object is a passive data structure that contains abstract descriptions of the operations to be executed. Intent transmission between different components has different mechanisms:

  • Pass an intent to contex. startactivity () or activity. atartactivityforresult () to run a new activity or obtain an existing activity to do something new (or pass it to the activity. setresult () to return information, which is the result that other activities want to obtain by calling the startactivityforresult () method ).
  • You can pass an intent to context. startservice () to initialize a service or send a new instruction (Instructions) to an ongoing service. Similarly, an intent can be passed to context. bindservice () to establish a connection between the calling component and the target service. It can initialize services that are not running at will.
  • Transmit intent to any broadcast method (such as context. sendbroadcast (), context. sendorderedbroadcast (), or context. sendstickybroadcast () to all interested broadcast referers. Many broadcas are derived from system code.

 

In each case, the android system will find the appropriate activity, service or broadcast receiverl to respond to intent and instantiate it as needed. These information systems do not overlap: the broadcast intent will only be passed to the broadcast receiver and will never be passed to the activity or service.

Intent object

An intent object is a package of some information. It contains information of interest to the component that receives the intent (such as the action to be executed and the required data ), it also contains additional information of interest to the Android system (for example, it can receive the category of the intent component and how to load the command of a target activity ). Intent mainly includes the following content:

 

Component name

The name of the component to receive the intent. This field is a componentname object-a complete Class Name (such as "com. example. project. app. freneticactivity ") and the package name (for example," com. example. project. The component name is optional. If the component name is set, the intent object is passed to the instance of the specified class. If no component name is set, Android uses other information in intent to locate the appropriate target.

Setcomponent (), setclass (), or setclassname () are commonly used to set the component name, And getcomponent () is used to read the component name.

 

Action

Use a string to name the executed action. The intent class defines some action constants as follows:

Constant

Target component

Action)

Action_call

Activity

Initialize a call

Action_edit

Activity

Display data for users to edit

Action_main

Activity

Start the initial activity of a tast, neither input data nor output data.

Action_sync

Activity

Synchronize the data in the service with the data in the mobile phone device.

Action_battery_low

Broadcast receiver er

Warning power usage too low

Action_headset_plug

Broadcast receiver er

The headset is moved in or out of the device.

Action_screen_on

Broadcast receiver er

Screen off

Action_timezone_changed

Broadcast receiver er

Change the time zone settings

Other action declarations are distributed in other parts of the android API. You can also define your own action string. In this case, you need to prefix the application package name as your action string. For example, "com. example. Project. show_color ". The action field largely determines other intent structures-especially the data field and extras field-as the function name determines the form parameter and return value. Therefore, it is a good idea to make the action name as clear as possible and closely associate it with other intent fields.

Set the intent action through setaction () and read it using getaction.

 

Data

The URI or MIME type of the data to be processed. Different actions have different data specifications. For example, if the action field is action_edit, the data field should contain the URI of the document to be displayed and edited. If the action field is action_call, the data field should be a Tel: uri containing the number to be called. If the action field is action_view, the data field should be an http: URI that receives the data to be downloaded and displayed by the activity.

When processing an intent, it is often important to know its data type (its MIME type) except Uri. For example, a component that can display images cannot be used to play music.

In many cases, the data type can be inferred from its URI ----- especially content: Uris, which indicates that the data is in a device and controlled by the content provider. However, the type can also be explicitly set in the intent object. The setdata () method only specifies the data URI. The settype () method specifies the data MIME type. The setdataandtype () method sets the data Uri and MIME types. You can use getdata () to obtain the data and GetType () to obtain the data type.

 

 

Category

 

 

The string that can receive the category of the intent component. Multiple category strings can be placed in the intent object. Intent classes are defined 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.

Use addcategory () to set a category to the intent object. removecategory () deletes a previously added category. getcategories () gets all the category in the current intent object.

Extras

Additional information that exists as a key-value pair to be passed to the target component. Just as some actions are paired with data Uris, actions must also match extras. For example, an action_timezone_changed intent has a "time-zone" extra to indicate the new time zone, and an action_headset_plug has a "state" extra to indicate whether the headset is inserted or pulled out, and "name" extra to specify the headset type. If you want to customize a show_color action, the color value will be set to extra key-value pair.

The intent object has a series of methods like putxxx () or getxxx () to set or retrieve different types of extra data. These methods are similar to bundle objects. In fact, extra can be loaded or read as a bundle object, using the putextras () and getextras () methods.

Flags

Various flags. Many specify how the Android system loads an activity and how to handle it after loading (for example, whether it belongs to the latest activity list ). All flags are defined in the intent class.

 

Intent Solution

Intent can be divided into two groups:

  • Explicit intentsUse the name of the target component. Because developers of other programs generally do not know the component name, explicit it intent is often used for messages within the program-for example, an activity starts a ancillary service or loads a sibling activity.
  • Implicit intentsThe component name is not specified (the component name field is empty ). It is often used to activate components of other programs.

When Android transmits an explicit it intent to an instance of the class of the specified target component, the component name field in the intent object is crucial for determining which component should receive the intent.

Another different policy requires implicit intents. Because no target is specified, the android system must find the most appropriate component to process this intent. --- A single activity or service is used to execute the requested action or broadcast receiver to respond to the boardcast announcement. Use the intent object content and intent flilter (components related to the structure used to receive intent ). The filter publishes the capabilities of the component and limits the intent that can be processed. They can receive published implicit
Intents components are open.If a component does not have any intent filter, it can only receive the explicit intent. A filter component can receive both implicit intents and explicit intent.

Intent only has three fields: Action, data (Uri and data type), and category. Extras and flags do not work when parsing which component can receive this intent.

Intent Filter

To notify the system of implicit intents that can be processed, activity, service, and broadcast Uploader can have one or more intent filters. Each intent filter describes the capabilities of a component and the intent set they are willing to receive. Receive the intent they need and filter out intent (only implicit intents) that they do not want to receive ). Explicit intent must be passed to its target, whether or not it contains the intent filter.

A component has a separate fliter for each task.

An intent filter is an instance of the intentfilter class. However, because the Android system must know the capabilities of this component before loading the component, intent filter is often not created in Java code, but in the manifest file of the application (androidmanifest. XML) to set the <intent-filter> element. (One exception is that the filter of broadcast Receiver calls context. registerreceiver () for Dynamic Registration. They are directly created as intentfilter objects ).

A filter has fields similar to the action, data, and category of an intent object. An implicit intent passed to this component will be checked to see if the three fields match. Once an Android system does not match, the intent will not be passed to the component.

3. The test details are as follows:

Action Test

Use the <intent-filter> sub-element <action>, 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 the intent object can only have one action,However, a filter object can have multiple actions. A filter must contain at least one <action>; otherwise, it blocks all intents.

To pass this test, the acyion In the intent object must match the action list in the filter. If no action is specified for the intent object or filter, the result is as follows:

  • Action is not specified for filter, and all intent cannot pass
  • If no action is specified for an intent, the test is passed. As long as the filter contains at least one <action>

CATEGORY Test

<intent-filter . . . >    <category android:name="android.intent.category.DEFAULT" />    <category android:name="android.intent.category.BROWSABLE" />    . . .</intent-filter>
 

Note that the constants of action and category described in the previous section are not used in the manifest file. Instead, it is a complete string value. For example"android.intent.category.BROWSABLE"CorrespondingCATEGORY_BROWSABLEConstant. Similarly ,"android.intent.action.EDIT"CorrespondingACTION_EDITConstant.

If an intent wants to pass the test, all its category must match the filter. Filters can contain additional category, but do not omit any category in intent.

In principle, an intent without category can always pass the test without considering what is included in the filter. However, there is one exception: if implicit intents has"android.intent.category.DEFAULT"Category (CATEGORY_DEFAULTConstant), Android will pass them to startactivity (), so the activity that wants to receive implicit intents must contain"android.intent.category.DEFAULT". (Owns"android.intent.action.MAIN"And"android.intent.category.LAUNCHER"Filters are an exception. They indicate that the activity starts a new task and are displayed on the program loading interface. They can contain"android.intent.category.DEFAULT", But you do not need to do this ).

Data Test

<DATA> sub-tags, which can have multiple or none.

<intent-filter . . . >    <data android:mimeType="video/mpeg" android:scheme="http" . . . />     <data android:mimeType="audio/mpeg" android:scheme="http" . . . />    . . .</intent-filter>

Each <DATA> element can specify the URI and data type (MIME media type ). Uri has some separate attributes --scheme,host,port, Andpath.

Scheme: // host: Port/path

For example, the following URI:

Content: // com. example. Project: 200/folder/subfolder/etc

The section of the URI described above is: Scheme is"content", Host is"com.example.project", Port is"200", Path is"folder/subfolder/etc".

The host and port form a URI.Authority(Permission ). If the host is not specified, the port is ignored.

Each attribute is optional, but it is not independent from other attributes. scheme must be specified for authority purposes, and scheme and authority must be specified for path purposes.

When the URI of the intent object is compared with the URI in the filter, only part of the URI in the filter is compared. For example, if a filter only specifies scheme, all Uris containing this scheme match this filter. If a filter only specifies scheme and authority but does not have a path, all Uris containing the scheme and authority match the filter. If the filter specifies scheme, authority, and path, and only the scheme of the intent Uri,
It can be passed only when both authority and path match. However, a path can contain wildcards to allow matching of some paths.

The tyoe attribute of the <DATA> element specifies the MIME type of the data. Filters are more common than Uris. Both the intent object and filter can use the "*" wildcard in the child Type field, for example, "text/*" or "audio/*" -------- to identify all child types.

The data test compares the URI and Data Type of the intent object and the filter. The rules are as follows:

A. If an intent object does not contain a URI or a data type, the test can be performed only when the filter does not specify a URI or a data type.

B. if an intent object contains a URI but does not contain a data type (and the data type cannot be inferred from the URI ), the test can be performed only when the URI specified by the filter is matched and the filter does not specify the data type. These situations are only applicable to scenarios suchmailto:Andtel:There is no URI pointing to the actual data.

C. If an intent object does not contain a URI but contains a data type, you can use

D. if an intent object contains both the URI and the data type (or the data type can be inferred from the URI), the test must be: the data type can be matched, and Uri matching or filter supports content: or file: URI, and the filter does not specify the URI. In other words, when a filter has only the data type, it is assumed to support content: and file: data.

If an intent can use more than one activity or service, the system will ask which component can be selected for processing. If no match exists, an exception is thrown.

 

General situation:

The last one shown above shows the test and rules, reflecting that the component can obtain local data from the file or content provider. Therefore, a filter can only specify the data type without explicit naming.content:Andfile:Scheme. This is a typical situation. For example, the following <DATA> element tells the system that this component can receive and display image data from the content provider.

<data android:mimeType="image/*" />
 

Because most of the available data is allocated by the content provider, the filter with the specified data type but not the URI may be the most common..

Another common setting is to specify the scheme and Data Type filters. For example, the following <DATA> element tells the system that this component can obtain vedio from the Internet and play it back.

 

Consider what the browser program will do when a user clicks a link on a webpage. First, it tries to display the data. If the data cannot be displayed, it collects an implicit intent with the specified scheme and data type, and tries to start an activity that can do this. If there are no contacts,

It will require the Download Manager to download data. This will have a content provider to control it, so a potentially large number of activities (those that contain filters that only specify the Data Type) can respond.

Most applications can be restarted without any special data. You can specify the action"android.intent.action.MAIN". If they are expressed in the program loader, they will specify"android.intent.

<intent-filter . . . >    <action android:name="code android.intent.action.MAIN" />    <category android:name="code android.intent.category.LAUNCHER" /></intent-filter>

Match with intent:

Matching intent with intent filter is not only used to discover the target component to process the intent, but also used to send some information about the component on the device. Ratio

For example, the android system will search for all"android.intent.action.MAIN"Action and"android.intent.category.LAUNCHER"Intent filter activity of category. Then, add the icons of these activities to the Application Loader. Similarly, in order to discover the main screen, it looks"android.intent.category.HOME"Filter activity.

Your application can be loaded using intent in a similar way. Packagemanager has some queryxxx () Methods to return all components that can receive a specific intent. For example,queryIntentActivities()Return all intent activities that can be passed as parameters.queryIntentServices()Returns a similar service.

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.