My Android note--intent (I am the document Porter)

Source: Internet
Author: User

I am a porter of documents. Intent, intent, is a message-passing object. The most common intention for intent is to jump from one activity to another activity, or start a service, send a broadcast, and so on. It is divided into explicit intent and implicit intent, and the following is an explanation given by the API guide.
    • Explicit Intent : Specifies the component to start by name (fully qualified class name). Typically, you use explicit Intent in your app to start a component because you know the class name of the Activity or service you want to start. For example, start a new Activity in response to a user action, or start a service to download files in the background.
    • implicit Intent : Does not specify a specific component, but rather declares the general action to be performed, allowing components in other applications to handle it. For example, if you want to show a location to a user on a map, you can use implicit Intent to request another app with this feature to display the specified location on the map.
When you create an explicit intent, the application component specified by the intent object is started immediately.     When you create an implicit intent, the Android system finds the appropriate component to start by comparing the content of intent with the intent filter declared by the manifest file for other apps on the device. It is important to note that you do not use implicit intent to start the service, after API21 (5.0), if the implicit intent to call Bindservice () throws an exception. Build IntentIntent, the object carries the information that the Android system uses to determine which component to start. The main information it contains is as follows. are copied and pasted from the API.
Component Name
The name of the component to start.

This is optional, but is also an important piece of information for building explicit Intent, which means that Intent should only be passed to the application component defined by the component name. If there is no component name, Intent is implicit and the system determines which component should receive Intent based on other Intent information, such as the actions, data, and categories described below. Therefore, if you want to start a particular component in your app, you should specify the name of the component.

Note: Service When you start, you should always specify a component name . Otherwise, you cannot determine which service responds to Intent, and users cannot see which service is started.

Intentis an ComponentName object, you can specify this object with the fully qualified class name of the target component, which includes the package name of the app. For example, com.example.ExampleActivity . You can set the component name by using the setComponent() , setClass() ,, setClassName() or Intent constructor function.

Operation
A string that specifies the generic action to perform (for example, "View" or "pick").

For broadcast Intent, this refers to the action that has occurred and is being reported. The operation largely determines the composition of the remaining Intent, especially the content contained in the data and extra.

You can specify your own actions for Intent to use within your app (or for other apps to call components in your app). However, you should typically use Intent an action constant defined by a class or other framework class. Here are some common actions to start the Activity:

ACTION_VIEW
If you have some information that an activity can display to users (for example, photos you want to view using the Gallery app, or you want to use the Map app to find the address), use Intent to combine this action with startActivity() .
ACTION_SEND
This is also known as the "shared" Intent. If you have data that users can share through other apps, such as email apps or social sharing apps, you should use Intent to use this action in conjunction with startActivity() .

For more constants that define common operations, see Intent class references. Other operations are defined in other locations in the Android framework. For example, an action that opens a specific screen in the Settings app for the system is Settings defined in.

You can use setAction() or Intent construct a function to specify an action for Intent.

If you define your own actions, be sure to prefix the package names you apply. For example:

Static final String Action_timetravel = "Com.example.action.TIMETRAVEL";
Data
A URI (object) that references the data to be manipulated and/or the MIME type of the data Uri . The type of data provided is usually determined by the operation of Intent. For example, if the action is ACTION_EDIT , the data should contain the URI of the document you want to edit.

When creating Intent, specifying a data type (its MIME type) is often important in addition to specifying a URI. For example, an activity that can display an image may not play an audio file, even if the URI format is very similar. Therefore, specifying the MIME type of the data helps the Android system find the best component to receive Intent. Sometimes, however, MIME types can be inferred from URIs, especially when the data is a content: URI. This indicates that the data resides in the device and is ContentProvider controlled, which makes the data MIME type visible to the system.

To set the data URI only, call setData() . To set only MIME types, call setType() . If necessary, you can use setDataAndType() both to explicitly set both.

Warning: to set both the URI and MIME type, do not invoke setData() and setType() because they will cancel each other's values. Always use setDataAndType() both to set the URI and MIME type.

Category
A string that contains additional information that should handle the Intent component type. You can put any number of category descriptions in one Intent, but most Intent do not require a category. Here are some common categories:
CATEGORY_BROWSABLE
The target Activity allows itself to be launched through a Web browser to display links to referenced data, like or e-mail.
CATEGORY_LAUNCHER
The activity is the initial activity of the task, listed in the Application Launcher of the system.

For a complete list of categories, see Intent class descriptions.

You can use the addCategory() specified category.

These attributes (component names, operations, data, and categories) listed above represent the established characteristics of Intent. By reading these properties, the Android system can resolve which application component should be started.

However, Intent is also likely to carry information that does not affect how it resolves to an application component. Intent can also provide:

Extra

A key-value pair that carries additional information required to complete the request operation. Just as some operations use a specific type of data URI, some operations also use specific additional data.

You can putExtra() add additional data using a variety of methods, each of which accepts two parameters: Key name and value. You can also create an object that contains all the additional data Bundle , and then use it putExtras() to Bundle insert Intent in.

For example, ACTION_SEND when you create a Intent to send an e-mail message, you can use the EXTRA_EMAIL key to specify the target recipient and use EXTRA_SUBJECT the key to specify the subject.

IntentClass will specify multiple constants for the normalized data type EXTRA_* . To declare your own additional Data key (for Intent received by your app), be sure to prefix the app's package name. For example:

Static final String Extra_gigawatts = "Com.example.EXTRA_GIGAWATTS";
logo

In IntentA flag that acts as a Intent metadata defined in a class. Flags can indicate how the Android system initiates activity (for example, which task the activity should belong to), and how to handle it after startup (for example, whether it belongs to the most recent activity list). For more information, please see setFlags()Method. an explicit Intent example

Explicit Intent refers to the Intent that is used to start a particular application component (for example, a specific Activity or service in an app). To create an explicit Intent, define the Intent component name for your object. All other properties of the Intent are optional.

For example, if you build a service in your app named DownloadService , designed to download files from the Web, you can start the service by using the following code:

Context
The FILEURL is a string URL, such as "Http://www.example.com/image.png"
Intent downloadintent = new Intent (this, downloadservice.class);
Downloadintent.setdata ( Uri.parse (FILEURL));
StartService (downloadintent);
Intent(Context, Class)Constructors are provided for applications and components, respectively ContextAnd ClassObject. Therefore, this Intent will explicitly start the application in the DownloadServiceClass. An implicit intent example

The implicit Intent specifies the ability to invoke any app operation on a device that can perform the appropriate action. If your app can't do this and other apps can, and you want the user to pick the app that you want to use, it's useful to use an implicit Intent.

For example, if you want users to share your content with others, use ACTION_SEND actions to create Intent and add Extra that specify shared content. When you use the Intent call startActivity() , the user can pick the app that is used to share the content.

Warning: The user may not have any apps that handle startActivity() the implicit Intent you send to. If this occurs, the call will fail and the app will crash. To verify that the Activity will receive Intent, Intent call the object resolveActivity() . If the result is non-null, at least one application will be able to handle the Intent and can be safely called startActivity() . If the result is empty, the Intent should not be used. If possible, you should disable the ability to emit the Intent.

Create the text message with a string
Intent sendintent = new Intent ();
Sendintent.setaction (Intent.action_send);
Sendintent.putextra (Intent.extra_text, textmessage);
Sendintent.settype ("Text/plain");

Verify that the intent would resolve to an activity
if (Sendintent.resolveactivity (Getpackagemanager ()) = null) {
StartActivity (sendintent);
}

Note: in this case, the system does not use a URI, but declares the Intent data type, which specifies what Extra carries.

Call startActivity(), the system checks all installed applications to determine which applications are capable of handling this Intent (i.e.: ACTION_SENDOperation and carry "text/plain" data Intent). If only one app can handle it, the app will open immediately and provide it to Intent. If multiple Activity accepts Intent, a dialog box is displayed that enables the user to select the app to use. Force the app Selector

If more than one app responds to an implicit Intent, the user can select the app to use and set it as the default option for that action. This is useful if a user might want to continue to perform an action with the same app in the future (for example, when a Web page is open, users tend to use only one Web browser).

However, if multiple apps can respond to Intent, and users might want to use a different app each time, you should explicitly display the Selector dialog box. The Selector dialog box asks the user to select the app to use each time the action is used (the user cannot select the default app for the action). For example, when an app uses an ACTION_SEND action to perform a "share", the user may need to use another different app depending on the current situation, so you should always use the Selector dialog box, as shown in 2.

To display the selector, use createChooser() Create and Intent pass it to startActivity() . For example:

Intent sendintent = new Intent (intent.action_send);
...

Always use the string resources for UI text.
This says something like "Share this photo with"
String title = Getresources (). getString (R.string.chooser_title);
Create intent to show the Chooser dialog
Intent chooser = Intent.createchooser (sendintent, title);

Verify The original intent would resolve to at least one activity
if (Sendintent.resolveactivity (Getpackagemanager ()) = null) {
StartActivity (chooser);
}
This displays a dialog box that contains the response passed to the createChooser()The Intent method lists the application and uses the provided text as the dialog box caption. Accept Implicit IntentTo advertise that an app can accept those implicit intent, you must declare one or more intent filters for the application component in the manifest file using Intent-filter. None of the intent filters specify the type of intent that they accept based on intent operations, data, and categories. The system will pass intent to the application component only when implicit intent can be passed through one of the intent filters. Of course, an explicit intent is always passed to its target, regardless of the intent of the component declaration. In the intent filter, you can use the value of three elements to specify the type of intent you want to accept. "Action" in the name attribute, declares the accepted intent action. The value must be the text string value of the operation, not the class is normally lit. "Data" declares the accepted data type by using one or more attributes of each facet and MIME type of the specified data URI (scheme, hosts, port, path, and so on). Category in the name attribute, declare the accepted intent category.     The value must be the text string value of the operation, not the class is normally lit. Note that in order to accept implicit intent. The Category_default category must be included in the intent filter. Methods StartActivity and Startactivityforresult will handle all intent in the same manner as the declared Category_default category. If the sub-category is not declared in the intent filter, the implicit intent does not resolve to your activity.

For example, the following is an Activity declaration using the Intent filter, which receives Intent when the data type is Text ACTION_SEND :

<activity android:name= "Shareactivity" >
<intent-filter>
<action android:name= "Android.intent.action.SEND"/>
<category android:name= "Android.intent.category.DEFAULT"/>
<data android:mimetype= "Text/plain"/>
</intent-filter>
</activity> You can create an action that includes multiple actions,Data or Categorythe filter for the instance. When created, you only need to determine that the component can handle any and all combinations of these filter elements.

If you need to handle multiple Intent only with specific combinations of operations, data, and category types, you need to create multiple Intent filters.

Restricting access to components

When using the Intent filter, it is not safe to prevent other apps from starting the component. Although the Intent filter restricts the component to respond only to certain types of implicit Intent, if the developer determines your component name, other apps might start your app component by using an explicit Intent. If you must make sure that only your own app can start one of your components, exported set the property to for that component "false" .

The system tests the implicit Intent based on a filter by comparing Intent with all three elements. Implicit Intent to pass to the component, all three tests must pass. If Intent does not even match any of these tests, the Android system does not pass it on to the component. However, because a component may have multiple Intent filters, Intent that fail through a component filter may pass through another filter. For more information on how the system resolves Intent, see the Intent Resolution section below.

WARNING: to avoid inadvertently running different apps Service , always use explicit Intent to start your own services without having to declare Intent filters for the service.

Note:For all Activity, you must declare the Intent filter in the manifest file. However, the filter for the broadcast receiver can be called by invoking the registerReceiver()Dynamic registration. Later, you can use unregisterReceiver()Unregisters the sink. This allows the app to listen for a specific broadcast only during a specified period of time when the app is running. using the pending intentThe Pendingintent object is the wrapper for the intent object. The main purpose of Pendingintent is to authorize an external application to use the included intent, just as it does from the process of the application itself.     The main use cases for pendingintent include: 1, declaring the user the execution required to perform an operation using your notification intent (Notificationmanager execution intent of the Android system)     2, declare the intent (main screen app execution intent) to execute when the user performs the action using your app's small public who 3, declaring the intent to be performed at a particular time in the future (Alarmmanager execution intent of the Android system) because each intent object is designed to be processed by a particular type of application component (Activity, Service or Broadcastreceiver), you must also create a pendingintent based on the same considerations. When using a pending intent, the app does not execute the intent using a call such as startactivity. Instead, when you create pendingintent by calling the appropriate creator method, you must declare the type of component that you want.
    • PendingIntent.getActivity(), which is suitable for start Activity -up Intent .
    • PendingIntent.getService(), which is suitable for start Service -up Intent .
    • PendingIntent.getBroadcast(), which is suitable for start BroadcastReceiver -up Intent .

Unless your app is receiving pending Intent from other apps, the PendingIntent method above might be the only way you need to create it PendingIntent .

Each method extracts the current app Context , which you want to wrap, Intent and one or more flags that specify how the Intent should be used (for example, if the Intent can be used more than once).

For more information about using the pending Intent, see the documentation for each of the appropriate use cases in the manuals for notifications and app gadget API guides. Intent parsing

When the system receives an implicit Intent to initiate activity, it compares the Intent with the Intent filter according to the following three aspects, searching for the best Activity for that Intent:

    • Intent operation
    • Intent data (URI and data type)
    • Intent category

The following describes how Intent matches the corresponding component, based on how the Intent filter is declared in the application's manifest file.

Operational testing

To specify an accepted Intent action, the Intent filter can either declare no &lt;action&gt; elements or declare multiple such elements. For example:

<intent-filter>
<action android:name= "Android.intent.action.EDIT"/>
<action android:name= "Android.intent.action.VIEW"/>
...
</intent-filter>

To pass this filter, the action you Intent specify in will have to match one of the actions listed in the filter.

If the filter does not list any actions, Intent does not have any matches, so all Intent cannot pass the test. However, if Intent no action is specified, the test passes (as long as the filter contains at least one action).

Category Test

To specify an accepted Intent category, the Intent filter can either declare no &lt;category&gt; elements or declare multiple such elements. For example:

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

To Intent through a category test, Intent each category in the filter must match the category in the filters. Conversely, there is no certainty that the category that the Intent filter declares can exceed the Intent number specified in, and Intent will still pass the test. Therefore, Intent that do not contain categories should always pass this test, regardless of which category is declared in the filter.

Note: Android automatically applies the CATEGORY_DEFAULT category to startActivity() startActivityForResult() All implicit Intent that are passed to and. Therefore, if you want Activity to receive implicit Intent, you must "android.intent.category.DEFAULT" include the category in its Intent filter (as shown in the &lt;intent-filter&gt; example above).

Data testing

To specify accepted Intent data, the Intent filter can either declare no &lt;data&gt; elements or declare multiple such elements. For example:

<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 structure and data type (MIME media type). Each part of the URI contains a separate scheme , host ,, port and path attribute:

&lt;scheme&gt;://&lt;host&gt;:&lt;port&gt;/&lt;path&gt;

For example:

content://com.example.project:200/folder/subfolder/etc

In this URI, the schema is, the content host is, the com.example.project port is, the 200 path is folder/subfolder/etc .

In an &lt;data&gt; element, each of these properties is optional, but there are linear dependencies:

    • If no schema is specified, the host is ignored.
    • If no host is specified, the port is ignored.
    • If no schemas and hosts are specified, the path is ignored.

When a URI in Intent is compared to a URI specification in a filter, it is compared to only the partial URIs contained in the filter. For example:

    • If the filter specifies only the schema, all URIs that have that schema match the filter.
    • If the filter specifies schemas and permissions, but does not specify a path, all URIs with the same schema and permissions pass through the filter, regardless of their path.
    • If the filter specifies schemas, permissions, and paths, only URIs with the same schema, permissions, and Paths pass through the filter.

Note: The path specification can contain the asterisk wildcard character (*), so you only need to partially match the path name.

The data test compares the URI and MIME type in Intent with the URI and MIME type specified in the filter. The rules are as follows:

    1. Intent with no URI and MIME type will pass the test only if no URI or MIME type is specified by the filter.
    2. For Intent that contain URIs, but do not contain MIME types (which are not explicitly declared and cannot be inferred from URIs), the test passes only if its URI matches the URI format of the filter and the filter does not specify a MIME type.
    3. A Intent that contains a MIME type but does not contain a URI will pass the test only if the filter lists the same MIME type and does not specify a URI format.
    4. A Intent that contains a URI and MIME type (either explicitly declared, or can be inferred through a URI) will pass through the MIME type portion of the test only if the MIME type matches the type listed in the filter. If the URI of the Intent matches the URI in the filter, or if Intent has a URI and the content: file: filter does not specify a URI, Intent passes the URI portion of the test. In other words, if the filter lists only MIME types, the component support content: and data are assumed file: .

The last rule, rule (d), reflects the expected component to be able to obtain local data from the file or from the content provider. As a result, its filters can list only data types without having to explicitly name content: and file: schema. This is a typical case. For example, the &lt;data&gt; elements below indicate to Android that the component can obtain and display image data from the content provider:

<intent-filter>
<data android:mimetype= "image/*"/>
...
</intent-filter>

Because most of the available data is distributed by the content provider, filters that specify a data type, rather than a URI, may be the most common.

Another common configuration is a filter with schemas and data types. For example, the &lt;data&gt; elements below indicate to Android that the component can retrieve video data from the network to perform operations:

<intent-filter>
<data android:scheme= "http" android:type= "video/*"/>
...
</intent-filter>
Intent Matching

Matching the Intent with the Intent filter not only helps to discover which target component to activate, but also helps to discover information about the component set on the device. For example, the home Page app ACTION_MAIN populates the CATEGORY_LAUNCHER app launcher by finding all the Activity by using the Intent filter for the specified action and category.

Your app can use Intent matching in a similar way. PackageManagerProvides a complete set of query...()method to return all components that can accept a specific Intent. In addition, it provides a series of similar resolve...()method to determine the best component of the response Intent. For example queryIntentActivities()will return all Activity lists that can perform those Intent that are passed as parameters, and queryIntentServices()You can return a similar list of services. Neither of these methods activates the component, but simply lists the components that can respond. For broadcast receivers, there is a similar approach: queryBroadcastReceivers()。 In the API, there is a complete set of descriptions of the various features of intent. The following article writes about the common uses of intent.

My Android note--intent (I am the document Porter)

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.