码迷,mamicode.com
首页 > Windows程序 > 详细

API翻译 --- Intent and Intent Filters

时间:2016-07-19 10:24:54      阅读:318      评论:0      收藏:0      [点我收藏+]

标签:

IN THIS DOCUMENT

  1. Intent Types           目的类型
  2. Building an Intent        构建一个意图
    1. Example explicit intent       例子显式意图
    2. Example implicit intent      例隐式意图
    3. Forcing an app chooser        
      迫使应用程序选择器
  3. Receiving an Implicit Intent           收到一个隐式意图
    1. Example filters                例如过滤器
  4. Using a Pending Intent               使用一个悬而未决的意图
  5. Intent Resolution                     意图解析
    1. Action test                           动作测试
    2. Category test              类别测试
    3. Data test                     数据测试
    4. Intent matching               意图匹配

SEE ALSO

  1. Interacting with Other Apps              与其他应用交互
  2. Sharing Content                            内容共享






An Intent is a messaging object you can use to request an action from another app component. Although intents facilitate communication between components in several ways, there are three fundamental use-cases:

一个意图是一个消息传递对象可以使用从另一个应用程序组件请求一个动作。尽管意图促进组件之间的通信在几个方面,有三个基本用例:

  • To start an activity:

    An Activity represents a single screen in an app. You can start a new instance of an Activity by passing an Intent tostartActivity(). The Intent describes the activity to start and carries any necessary data.

    一个活动代表一个在应用程序屏幕。您可以启动一个新实例的活动通过一个意图tostartActivity()。目的描述了活动开始和携带任何必要的数据。

    If you want to receive a result from the activity when it finishes, callstartActivityForResult(). Your activity receives the result as a separate Intent object in your activity‘s onActivityResult()callback. For more information, see the Activities guide.

    如果你想收到活动结束时,结果callstartActivityForResult()。你的活动收到的结果作为一个单独的意图对象活动的onActivityResult()回调。有关更多信息,请参见活动指南。

  • To start a service:

    Service is a component that performs operations in the background without a user interface. You can start a service to perform a one-time operation (such as download a file) by passing an Intent to startService(). The Intent describes the service to start and carries any necessary data.

    一个服务是一个组件,执行操作在后台没有用户界面。您可以启动一个服务来执行一次操作(如下载一个文件)通过一个由startService()的意图。目的描述服务开始和携带任何必要的数据。

    If the service is designed with a client-server interface, you can bind to the service from another component by passing an Intent tobindService(). For more information, see the Services guide.

    如果服务客户机-服务器界面设计,你可以从另一个组件绑定到服务通过一个意图tobindService()。有关更多信息,请参见服务指南

  • To deliver a broadcast:           发表广播:

    A broadcast is a message that any app can receive. The system delivers various broadcasts for system events, such as when the system boots up or the device starts charging. You can deliver a broadcast to other apps by passing an Intent to sendBroadcast(),sendOrderedBroadcast(), or sendStickyBroadcast().

    一个广播消息,任何应用程序都可以接受。系统提供各种广播系统事件,如当系统启动或设备开始收费。你可以提供一个广播到其他应用程序通过一个意图sendBroadcast(),sendOrderedBroadcast(),或sendStickyBroadcast()。

Intent Types


There are two types of intents:                 有两种类型的意图:

  • Explicit intents specify the component to start by name (the fully-qualified class name). You‘ll typically use an explicit intent to start a component in your own app, 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 a file in the background.
  • 显式意图指定组件开始的名字(完全限定类名)。你通常使用一个显式意图开始一个组件在您自己的应用程序,因为您知道您想要的类名称的活动或服务开始。例如,开始一个新的活动来响应用户操作或启动一个服务在后台下载一个文件。

  • Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it. For example, if you want to show the user a location on a map, you can use an implicit intent to request that another capable app show a specified location on a map.
  • 隐式意图不命名一个特定的组件,而是宣布通用执行的行动,它允许一个组件从另一个应用程序来处理它。举个例子,如果你想让用户地图上的一个位置,您可以使用隐式意图来请求另一个能够应用程序显示一个地图上的指定位置。

When you create an explicit intent to start an activity or service, the system immediately starts the app component specified in the Intent object.

当您创建一个明确的意图开始一个活动或服务,系统立即启动应用程序组件对象中指定的意图。

技术分享

Figure 1. Illustration of how an implicit intent is delivered through the system to start another activity: [1] Activity A creates an Intent with an action description and passes it to startActivity()[2] The Android System searches all apps for an intent filter that matches the intent. When a match is found, [3] the system starts the matching activity (Activity B) by invoking itsonCreate() method and passing it the Intent.

图1所示。描述一个隐含的意图是通过系统启动另一个活动:[1]活动创建一个意图的行动描述并将其传递给startActivity()。[2]的Android系统搜索所有应用程序意图过滤器匹配的意图。当找到匹配,[3]系统开始匹配的活动(活动B)通过调用itsonCreate()方法并传递它的意图。

When you create an implicit intent, the Android system finds the appropriate component to start by comparing the contents of the intent to the intent filters declared in the manifest file of other apps on the device. If the intent matches an intent filter, the system starts that component and delivers it the Intent object. If multiple intent filters are compatible, the system displays a dialog so the user can pick which app to use.

当您创建一个隐式意图,Android系统找到适当的组件开始通过比较的内容在清单文件中声明的目的意图过滤器的其他应用程序在设备上。如果意图匹配一个意图过滤器,系统组件,并将其意图对象开始。如果多个意图过滤器是兼容,系统显示一个对话框,用户可以选择使用哪个应用程序。

An intent filter is an expression in an app‘s manifest file that specifies the type of intents that the component would like to receive. For instance, by declaring an intent filter for an activity, you make it possible for other apps to directly start your activity with a certain kind of intent. Likewise, if you do not declare any intent filters for an activity, then it can be started only with an explicit intent.
一个意图过滤器是一个表达式的应用程序清单文件,指定类型的组件将接收的意图。例如,通过声明一个意图过滤器为一个活动,你让其他应用程序直接与某种意图开始活动。同样地,如果你不申报任何意图过滤器为一个活动,然后可以开始只有一个明确的意图。

Caution: To ensure your app is secure, always use an explicit intent when starting a Service and do not declare intent filters for your services. Using an implicit intent to start a service is a security hazard because you cannot be certain what service will respond to the intent, and the user cannot see which service starts. Beginning with Android 5.0 (API level 21), the system throws an exception if you call bindService() with an implicit intent.

警告:确保你的应用程序是安全的,开始时总是使用一个显式意图服务,不为你的服务声明意图过滤器。使用隐式意图启动一个服务是一个安全隐患,因为你无法确定服务响应的目的,和用户不能看到哪些服务开始。从Android 5.0(API级别21)开始,系统会抛出异常,如果你叫bindService()与隐式意图。

Building an Intent


An Intent object carries information that the Android system uses to determine which component to start (such as the exact component name or component category that should receive the intent), plus information that the recipient component uses in order to properly perform the action (such as the action to take and the data to act upon).

意图对象携带信息,Android系统使用,以确定哪些组件开始(如具体的组件名称或组件类别应该接收意图),加上信息接收者组件使用为了正确执行的操作(如采取的行动和行动的数据)。

The primary information contained in an Intent is the following:

主要的信息包含在一个意图如下:

Component name             组件名称
The name of the component to start.             组件的名称开始。

This is optional, but it‘s the critical piece of information that makes an intent explicit, meaning that the intent should be delivered only to the app component defined by the component name. Without a component name, the intent is implicit and the system decides which component should receive the intent based on the other intent information (such as the action, data, and category—described below). So if you need to start a specific component in your app, you should specify the component name.

这是可选的,但是它的关键信息,意图明确,这意味着意图只能交付应用程序组件定义的组件名称。没有组件名称,目的是隐式的,系统决定哪个组件应该得到目的基于其他目的信息(如动作、数据和category-described下面)。所以,如果你需要在你的应用程序启动一个特定的组件,您应该指定组件的名称。

Note: When starting a Service, you should always specify the component name. Otherwise, you cannot be certain what service will respond to the intent, and the user cannot see which service starts.

注意:当开始一个服务时,您应该指定组件的名称。否则,你无法确定哪些服务将响应的目的,和用户不能看到哪些服务开始。

This field of the Intent is a ComponentName object, which you can specify using a fully qualified class name of the target component, including the package name of the app. For example, com.example.ExampleActivity. You can set the component name with setComponent()setClass()setClassName(), or with the Intentconstructor.

这一领域的意图是ComponentName对象时,您可以指定目标组件的使用完全限定类名,包括应用程序的包名称。例如,com.example.ExampleActivity。您可以设置组件名称与setComponent(),setClass(),setClassName(),或与Intentconstructor。

Action
A string that specifies the generic action to perform (such as view or pick).

In the case of a broadcast intent, this is the action that took place and is being reported. The action largely determines how the rest of the intent is structured—particularly what is contained in the data and extras.

一个字符串,指定通用行动执行(比如视图或选择)。
在广播意图的情况下,这是行动发生和被报道。行动在很大程度上决定了其余的意图是structured-particularly什么是包含在数据和临时演员。

You can specify your own actions for use by intents within your app (or for use by other apps to invoke components in your app), but you should usually use action constants defined by the Intent class or other framework classes. Here are some common actions for starting an activity:

你可以指定自己的行动意图使用在您的应用程序(或使用其他应用程序调用组件在应用程序),但是你应该通常使用常量定义的行动意图类或其他框架类。下面是一些常见的行动开始一个活动:

ACTION_VIEW
Use this action in an intent with startActivity() when you have some information that an activity can show to the user, such as a photo to view in a gallery app, or an address to view in a map app.
使用这个动作的意图startActivity()当你有一些活动可以显示给用户的信息,如一个画廊的照片查看应用程序,或一个地址查看地图应用程序。
ACTION_SEND
Also known as the "share" intent, you should use this in an intent with startActivity() when you have some data that the user can share through another app, such as an email app or social sharing app.
也被称为“共享”的意图,你应该使用这个在意图startActivity()当你有一些数据,用户可以共享通过另一个应用程序,如电子邮件应用程序或社会共享应用程序。

See the Intent class reference for more constants that define generic actions. Other actions are defined elsewhere in the Android framework, such as in Settings for actions that open specific screens in the system‘s Settings app.

的更多信息,请参见“意图类引用常量定义泛型操作。其他操作定义在Android框架的其他地方,比如在设置行动,开放系统中特定的屏幕的设置应用程序。

You can specify the action for an intent with setAction() or with an Intent constructor.

If you define your own actions, be sure to include your app‘s package name as a prefix. For example:

您可以指定的行动意图与setAction()或意图构造函数。
如果你定义自己的行为,一定要包括你的应用的包名作为前缀。例如:

staticfinalString ACTION_TIMETRAVEL ="com.example.action.TIMETRAVEL";
Data
The URI (a Uri object) that references the data to be acted on and/or the MIME type of that data. The type of data supplied is generally dictated by the intent‘s action. For example, if the action is ACTION_EDIT, the data should contain the URI of the document to edit.
引用的URI(URI对象)数据执行和/或数据的MIME类型。提供的数据类型通常是由意图的行动。例如,如果行动ACTION_EDIT,数据应该包含文档的URI来编辑。

When creating an intent, it‘s often important to specify the type of data (its MIME type) in addition to its URI. For example, an activity that‘s able to display images probably won‘t be able to play an audio file, even though the URI formats could be similar. So specifying the MIME type of your data helps the Android system find the best component to receive your intent. However, the MIME type can sometimes be inferred from the URI—particularly when the data is a content: URI, which indicates the data is located on the device and controlled by a ContentProvider, which makes the data MIME type visible to the system.

在创建一个意图时,通常是重要的指定类型的数据(它的MIME类型)除了它的URI。例如,一个活动,能够显示图像可能无法播放一个音频文件,即使URI的格式可以是相似的。因此指定MIME类型数据帮助Android系统找到最好的组件收到你的意图。然而,MIME类型有时可以推断出从URI-particularly当数据是一个内容:URI,这表明设备上的数据位于ContentProvider和控制,这使得数据MIME类型对系统来说是可见的。

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

只有数据URI,叫setData()。只设置MIME类型,调用setType()。如果有必要,你可以设置都明确setDataAndType()。

Caution: If you want to set both the URI and MIME type, do not call setData() and setType() because they each nullify the value of the other. Always use setDataAndType() to set both URI and MIME type.

警告:如果你想设置URI和MIME类型,不叫setData()和setType(),因为他们每一个废弃的价值。总是使用setDataAndType()来设置URI和MIME类型。

Category                    类别
A string containing additional information about the kind of component that should handle the intent. Any number of category descriptions can be placed in an intent, but most intents do not require a category. Here are some common categories:
一个字符串包含额外的信息关于这种组件应该处理的意图。任意数量的类别描述可以被放置在一个意图,但大多数意图不需要一个类别。下面是一些常见的类别:
CATEGORY_BROWSABLE
The target activity allows itself to be started by a web browser to display data referenced by a link—such as an image or an e-mail message.
目标活动允许本身是由一个web浏览器来显示数据引用link-such作为图像或电子邮件。
CATEGORY_LAUNCHER
The activity is the initial activity of a task and is listed in the system‘s application launcher.
的活动是最初的活动任务,系统的应用程序启动器中列出。

See the Intent class description for the full list of categories.   看到完整的意图类描述的类别列表。

You can specify a category with addCategory().      您可以指定一个类别与addCategory()。

These properties listed above (component name, action, data, and category) represent the defining characteristics of an intent. By reading these properties, the Android system is able to resolve which app component it should start.

上面列出的这些属性(组件名称、动作、数据和类别)表示目的的特征。通过阅读这些属性,Android系统是能够解决应用程序组件应该开始。

However, an intent can carry additional information that does not affect how it is resolved to an app component. An intent can also supply:

然而,意图可以携带更多的信息,不影响如何解决一个应用程序组件。一个意图也可以供应:

Extras
Key-value pairs that carry additional information required to accomplish the requested action. Just as some actions use particular kinds of data URIs, some actions also use particular extras.
键-值对携带所需的额外信息来完成请求的操作。就像一些操作使用特定类型的数据uri,一些操作也使用特定的临时演员。

You can add extra data with various putExtra() methods, each accepting two parameters: the key name and the value. You can also create a Bundle object with all the extra data, then insert the Bundle in the Intentwith putExtras().

您可以添加额外的数据与各种putExtra()方法,每个接受两个参数:名称和值的关键。您还可以创建一个包对象所有的额外的数据,然后插入的包Intentwith putExtras()。

For example, when creating an intent to send an email with ACTION_SEND, you can specify the "to" recipient with the EXTRA_EMAIL key, and specify the "subject" with the EXTRA_SUBJECT key.

例如,当创建一个意图与ACTION_SEND发送一封电子邮件,您可以指定的”到“收件人EXTRA_EMAIL键,并指定EXTRA_SUBJECT关键的“主题”。

The Intent class specifies many EXTRA_* constants for standardized data types. If you need to declare your own extra keys (for intents that your app receives), be sure to include your app‘s package name as a prefix. For example:

意图类指定许多EXTRA_ *常量标准化的数据类型。如果你需要声明自己的额外键(应用程序接收的意图),一定要包括你的应用的包名作为前缀。例如:

staticfinalString EXTRA_GIGAWATTS ="com.example.EXTRA_GIGAWATTS";
Flags
Flags defined in the Intent class that function as metadata for the intent. The flags may instruct the Android system how to launch an activity (for example, which task the activity should belong to) and how to treat it after it‘s launched (for example, whether it belongs in the list of recent activities).

For more information, see the setFlags() method.

旗帜意图类中定义的函数作为元数据的意图。国旗可能指示Android系统如何启动一个活动(例如,任务活动应该属于)以及如何在其启动之后把它(例如,是否属于最近的活动)的列表。
有关更多信息,请参见setFlags()方法。

Example explicit intent               例子显示意图

An explicit intent is one that you use to launch a specific app component, such as a particular activity or service in your app. To create an explicit intent, define the component name for the Intent object—all other intent properties are optional.

一个明确的意图是一个用来启动一个特定的应用程序组件,如一个特定的活动或服务在您的应用程序。创建一个明确的目的,定义的组件名称意图object-all其他意图属性是可选的。

For example, if you built a service in your app, named DownloadService, designed to download a file from the web, you can start it with the following code:

例如,如果你建立了一个服务应用程序,名为DownloadService,旨在从网上下载一个文件,你可以用下面的代码:

// Executed in an Activity, so ‘this‘ is the Context
// The fileUrl is a string URL, such as "http://www.example.com/image.png"

Intent downloadIntent =newIntent(this,DownloadService.class);
downloadIntent
.setData(Uri.parse(fileUrl));
startService
(downloadIntent);

The Intent(Context, Class) constructor supplies the app Context and the component a Class object. As such, this intent explicitly starts the DownloadService class in the app.

For more information about building and starting a service, see the Services guide.

目的(背景下,类)构造函数提供了应用程序上下文和组件类对象。因此,这个意图明确启动DownloadService类应用。
关于构建和启动一个服务的更多信息,见服务指南。

Example implicit intent     例子隐式意图

An implicit intent specifies an action that can invoke any app on the device able to perform the action. Using an implicit intent is useful when your app cannot perform the action, but other apps probably can and you‘d like the user to pick which app to use.

隐式意图指定一个动作,可以调用任何设备上的应用程序能够执行的行动。使用隐式意图是有用的应用程序不能执行操作时,但是其他的应用程序可能和你想让用户选择使用哪个应用程序。

For example, if you have content you want the user to share with other people, create an intent with theACTION_SEND action and add extras that specify the content to share. When you call startActivity() with that intent, the user can pick an app through which to share the content.

举个例子,如果你有内容您希望用户与他人分享,创建一个意图theACTION_SEND行动并添加额外指定内容分享。当你调用startActivity()与意图,用户可以选择一个应用程序,通过它来分享内容。

Caution: It‘s possible that a user won‘t have any apps that handle the implicit intent you send tostartActivity(). If that happens, the call will fail and your app will crash. To verify that an activity will receive the intent, call resolveActivity() on your Intent object. If the result is non-null, then there is at least one app that can handle the intent and it‘s safe to call startActivity(). If the result is null, you should not use the intent and, if possible, you should disable the feature that issues the intent.

警告:这是可能的,用户不会有任何应用程序处理隐式意图您发送tostartActivity()。如果出现这种情况,调用将失败,应用程序会崩溃。验证一个活动将得到意图,叫resolveActivity意图对象()。如果结果是null,那么至少有一个应用程序可以处理的意图和安全调用startActivity()。如果结果是空的,你不应该使用意图和,如果可能,您应该禁用功能,问题的意图。

// Create the text message with a string
Intent sendIntent =newIntent();
sendIntent
.setAction(Intent.ACTION_SEND);
sendIntent
.putExtra(Intent.EXTRA_TEXT, textMessage);
sendIntent
.setType(HTTP.PLAIN_TEXT_TYPE);// "text/plain" MIME type

// Verify that the intent will resolve to an activity
if(sendIntent.resolveActivity(getPackageManager())!=null){
    startActivity
(sendIntent);
}

Note: In this case, a URI is not used, but the intent‘s data type is declared to specify the content carried by the extras.

注意:在这种情况下,没有使用一个URI,但意图的声明数据类型指定内容由临时演员。

When startActivity() is called, the system examines all of the installed apps to determine which ones can handle this kind of intent (an intent with the ACTION_SEND action and that carries "text/plain" data). If there‘s only one app that can handle it, that app opens immediately and is given the intent. If multiple activities accept the intent, the system displays a dialog so the user can pick which app to use..

当startActivity()被调用时,系统检查所有已安装的应用程序,以确定哪些可以处理这种意图(ACTION_SEND行动的意图,携带“文本/普通”数据)。如果只有一个应用程序可以处理它,立即应用程序打开,是考虑到意图。如果多个活动接受意图,系统显示一个对话框,用户可以选择使用哪个应用程序。

技术分享

Figure 2. A chooser dialog.                           一个选择器对话框。

Forcing an app chooser                   迫使应用程序选择器

When there is more than one app that responds to your implicit intent, the user can select which app to use and make that app the default choice for the action. This is nice when performing an action for which the user probably wants to use the same app from now on, such as when opening a web page (users often prefer just one web browser) .

当有多个应用程序响应你的隐式意图,用户可以选择使用哪个应用程序,使应用程序的默认选择的行动。这是好当执行一个操作的用户可能希望使用相同的应用程序从现在开始,比如当打开一个web页面(用户通常只喜欢一个web浏览器)。

However, if multiple apps can respond to the intent and the user might want to use a different app each time, you should explicitly show a chooser dialog. The chooser dialog asks the user to select which app to use for the action every time (the user cannot select a default app for the action). For example, when your app performs "share" with the ACTION_SEND action, users may want to share using a different app depending on their current situation, so you should always use the chooser dialog, as shown in figure 2.

然而,如果多个应用程序可以应对意图和用户可能想要使用一个不同的应用程序每一次,你应该明确地显示一个选择器对话框。选择器对话框让用户选择使用哪个应用程序的每次行动(行动的用户不能选择一个默认的应用程序)。例如,当你的应用程序执行“分享”ACTION_SEND行动,用户可能想要分享使用不同的应用程序根据其现状,所以你应该始终使用选择器对话框中,如图2所示。

To show the chooser, create an Intent using createChooser() and pass it tostartActivity(). For example:

显示选择器,创建一个意图使用createChooser()并将其传递给tostartActivity()。例如:

Intent sendIntent =newIntent(Intent.ACTION_SEND);
...

// Always use 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 will resolve to at least one activity
if(sendIntent.resolveActivity(getPackageManager())!=null){
    startActivity
(chooser);
}

This displays a dialog with a list of apps that respond to the intent passed to the createChooser() method and uses the supplied text as the dialog title.

这将显示一个对话框的列表应用程序响应意图传递给createChooser()方法并使用提供的文本标题的对话框。

Receiving an Implicit Intent     发送一个隐式意图


To advertise which implicit intents your app can receive, declare one or more intent filters for each of your app components with an <intent-filter> element in your manifest file. Each intent filter specifies the type of intents it accepts based on the intent‘s action, data, and category. The system will deliver an implicit intent to your app component only if the intent can pass through one of your intent filters.

隐式意图应用程序可以接收广告,声明一个或多个意图过滤器为每个应用程序组件与一个在你的清单文件< intent-filter >元素。每个意图过滤器指定类型的意图基于意图的行为,它接受数据和类别。系统将您的应用程序组件提供一个隐式意图只有你意图的意图可以通过一个过滤器。

Note: An explicit intent is always delivered to its target, regardless of any intent filters the component declares.

注意:一个明确的意图总是传递给它的目标,无论任何意图过滤器组件声明。

An app component should declare separate filters for each unique job it can do. For example, one activity in an image gallery app may have two filters: one filter to view an image, and another filter to edit an image. When the activity starts, it inspects the Intent and decides how to behave based on the information in the Intent (such as to show the editor controls or not).

应用程序组件应该宣布独立的过滤器为每一个独特的工作可以做。例如,一个活动在一个图片库应用程序有两个过滤器:一个过滤器来查看图像,另一个过滤器来编辑图像。当活动开始时,它检查意图和行为决定如何基于意图的信息(如显示编辑器控件)。

Each intent filter is defined by an <intent-filter> element in the app‘s manifest file, nested in the corresponding app component (such as an <activity> element). Inside the <intent-filter>, you can specify the type of intents to accept using one or more of these three elements:

每个意图过滤器被定义为一个< intent-filter >元素的应用程序清单文件,嵌套在相应的应用程序组件(比如<活动>元素)。在< intent-filter >,您可以指定类型的意图接受使用这三个元素的一个或多个:

<action>
Declares the intent action accepted, in the name attribute. The value must be the literal string value of an action, not the class constant.
声明意图行动接受,在name属性。文字字符串值的值必须是一个动作,而不是类常量。
<data>
Declares the type of data accepted, using one or more attributes that specify various aspects of the data URI (schemehostportpath, etc.) and MIME type.
声明的数据类型接受,使用一个或多个属性指定的各个方面数据URI(计划、主机、端口、路径,等等)和MIME类型。
<category>
Declares the intent category accepted, in the name attribute. The value must be the literal string value of an action, not the class constant.
声明意图类别接受,在name属性。文字字符串值的值必须是一个动作,而不是类常量。

Note: In order to receive implicit intents, you must include the CATEGORY_DEFAULT category in the intent filter. The methods startActivity() and startActivityForResult() treat all intents as if they declared theCATEGORY_DEFAULT category. If you do not declare this category in your intent filter, no implicit intents will resolve to your activity.

注意:为了得到隐含的意图,你必须包括CATEGORY_DEFAULT类别的意图过滤器。方法startActivity()和startActivityForResult()对所有的意图,好像他们宣布theCATEGORY_DEFAULT类别。如果你不声明这类意图过滤器,没有隐式意图将解决你的活动。

For example, here‘s an activity declaration with an intent filter to receive an ACTION_SEND intent when the data type is text:

举例来说,这里的一个活动声明意图过滤器接收一个ACTION_SEND意图时,数据类型是文本:

<activityandroid:name="ShareActivity">
   
<intent-filter>
       
<actionandroid:name="android.intent.action.SEND"/>
       
<categoryandroid:name="android.intent.category.DEFAULT"/>
       
<dataandroid:mimeType="text/plain"/>
   
</intent-filter>
</activity>

It‘s okay to create a filter that includes more than one instance of <action><data>, or <category>. If you do, you simply need to be certain that the component can handle any and all combinations of those filter elements.

可以创建一个过滤器,包括多个实例的<行动>、<数据>或<目录>。如果你这样做,你只是需要特定的组件可以处理任何和所有这些过滤器的组合元素。

When you want to handle multiple kinds of intents, but only in specific combinations of action, data, and category type, then you need to create multiple intent filters.

当你想要处理多个种类的意图,但只有在特定的组合动作,数据,和分类类型,那么您需要创建多个意图过滤器。

Restricting access to components               限制访问组件

Using an intent filter is not a secure way to prevent other apps from starting your components. Although intent filters restrict a component to respond to only certain kinds of implicit intents, another app can potentially start your app component by using an explicit intent if the developer determines your component names. If it‘s important thatonly your own app is able to start one of your components, set the exportedattribute to "false" for that component.

使用一个过滤器的目的不是一种安全的方法,以防止其他应用程序组件。尽管意图过滤器限制组件响应只有某些类型的隐式意图,另一个应用程序可以启动你的应用程序组件通过使用一个显式意图如果开发人员决定您的组件名称。如果重要的是有自己的应用程序可以开始你的一个组件,将exportedattribute设置为“false”组件。

An implicit intent is tested against a filter by comparing the intent to each of the three elements. To be delivered to the component, the intent must pass all three tests. If it fails to match even one of them, the Android system won‘t deliver the intent to the component. However, because a component may have multiple intent filters, an intent that does not pass through one of a component‘s filters might make it through on another filter. More information about how the system resolves intents is provided in the section below about Intent Resolution.

隐式意图对过滤器通过对比测试意图的三个元素。交付到组件,意图必须通过所有三个测试。如果不能匹配即使其中之一,Android系统的意图,不会送到组件。然而,由于一个组件可能有多个意图过滤器,一个意图,不经过一个组件的一个过滤器可能会使它在另一个过滤器。更多信息系统如何解决意图小节中提供了关于意图解决。

Caution: To avoid inadvertently running a different app‘s Service, always use an explicit intent to start your own service and do not declare intent filters for your service.

警告:为了避免无意中运行不同的应用程序的服务,始终使用一个显式意图开始自己的服务,不为您的服务声明意图过滤器。

Note: For all activities, you must declare your intent filters in the manifest file. However, filters for broadcast receivers can be registered dynamically by calling registerReceiver(). You can then unregister the receiver withunregisterReceiver(). Doing so allows your app to listen for specific broadcasts during only a specified period of time while your app is running.

注:所有活动,你必须声明意图过滤器在manifest文件中。然而,过滤器可以动态注册广播接收器通过调用registerReceiver()。然后你可以注销接收者withunregisterReceiver()。这样做可以让你的应用程序监听特定的广播只在指定的时间内,你的应用程序正在运行。

Example filters

To better understand some of the intent filter behaviors, look at the following snippet from the manifest file of a social-sharing app.

为了更好地理解一些行为意图过滤器,看看下面的代码片段从一个社交分享应用程序清单文件。

<activityandroid:name="MainActivity">
   
<!-- This activity is the main entry, should appear in app launcher -->
   
<intent-filter>
       
<actionandroid:name="android.intent.action.MAIN"/>
       
<categoryandroid:name="android.intent.category.LAUNCHER"/>
   
</intent-filter>
</activity>

<activityandroid:name="ShareActivity">
   
<!-- This activity handles "SEND" actions with text data -->
   
<intent-filter>
       
<actionandroid:name="android.intent.action.SEND"/>
       
<categoryandroid:name="android.intent.category.DEFAULT"/>
       
<dataandroid:mimeType="text/plain"/>
   
</intent-filter>
   
<!-- This activity also handles "SEND" and "SEND_MULTIPLE" with media data -->
   
<intent-filter>
       
<actionandroid:name="android.intent.action.SEND"/>
       
<actionandroid:name="android.intent.action.SEND_MULTIPLE"/>
       
<categoryandroid:name="android.intent.category.DEFAULT"/>
       
<dataandroid:mimeType="application/vnd.google.panorama360+jpg"/>
       
<dataandroid:mimeType="image/*"/>
       
<dataandroid:mimeType="video/*"/>
   
</intent-filter>
</activity>

The first activity, MainActivity, is the app‘s main entry point—the activity that opens when the user initially launches the app with the launcher icon:

MainActivity,第一个活动是打开的应用程序的主要入口这样活动最初当用户启动应用程序启动图标:

  • The ACTION_MAIN action indicates this is the main entry point and does not expect any intent data.
  • ACTION_MAIN行动表明这是主入口点和不期望任何意图的数据。
  • The CATEGORY_LAUNCHER category indicates that this activity‘s icon should be placed in the system‘s app launcher. If the <activity> element does not specify an icon with icon, then the system uses the icon from the<application> element.
  • CATEGORY_LAUNCHER范畴表明该活动的图标应放置在系统的应用程序启动器。如果<活动>元素没有指定一个图标,图标,然后系统使用的图标从<应用>元素。

These two must be paired together in order for the activity to appear in the app launcher.

The second activity, ShareActivity, is intended to facilitate sharing text and media content. Although users might enter this activity by navigating to it from MainActivity, they can also enter ShareActivity directly from another app that issues an implicit intent matching one of the two intent filters.

这两个必须成对在一起为了活动出现在应用程序启动器。
第二个活动,ShareActivity,旨在促进共享文本和媒体内容。虽然用户可能进入这个活动从MainActivity导航到它,也可以从另一个应用程序,直接进入ShareActivity问题隐式意图匹配的两个意图过滤器。

Note: The MIME type, application/vnd.google.panorama360+jpg, is a special data type that specifies panoramic photos, which you can handle with the Google panorama APIs.

注意:MIME类型,应用程序/ vnd.google。panorama360 + jpg,是一种特殊的数据类型,指定全景照片,您可以处理谷歌全景api。

Using a Pending Intent


PendingIntent object is a wrapper around an Intent object. The primary purpose of a PendingIntent is to grant permission to a foreign application to use the contained Intent as if it were executed from your app‘s own process.

PendingIntent对象是一个包装一个意图对象。PendingIntent的主要目的是允许外国应用程序来使用所包含的意图就像从你的应用程序的执行过程。

Major use cases for a pending intent include:            主要用例悬而未决的目的包括:

  • Declare an intent to be executed when the user performs an action with your Notification (the Android system‘sNotificationManager executes the Intent).
  • 声明一个意图,当用户执行一个动作执行你的通知(Android系统‘sNotificationManager执行意图)。
  • Declare an intent to be executed when the user performs an action with your App Widget (the Home screen app executes the Intent).
  • 声明一个意图执行当用户与应用程序执行一个动作小部件(主屏幕应用程序执行的意图)。
  • Declare an intent to be executed at a specified time in the future (the Android system‘s AlarmManager executes the Intent).
  • 声明一个意图在未来在指定的时间执行(Android系统的AlarmManager执行意图)。

Because each Intent object is designed to be handled by a specific type of app component (either an Activity, aService, or a BroadcastReceiver), so too must a PendingIntent be created with the same consideration. When using a pending intent, your app will not execute the intent with a call such as startActivity(). You must instead declare the intended component type when you create the PendingIntent by calling the respective creator method:

因为每个设计意图对象是由一个特定类型的应用程序组件(一个活动、服务或BroadcastReceiver),所以也必须PendingIntent创建相同的考虑。使用悬而未决的意图时,应用程序不会执行意图等电话startActivity()。你必须声明意图组件类型创建PendingIntent通过调用相应的创造者的方法:

  • PendingIntent.getActivity() for an Intent that starts an Activity.
  • PendingIntent.getService() for an Intent that starts a Service.
  • PendingIntent.getBroadcast() for a Intent that starts an BroadcastReceiver.

Unless your app is receiving pending intents from other apps, the above methods to create a PendingIntent are the only PendingIntent methods you‘ll probably ever need.

除非应用程序接收等待意图从其他应用程序,上面的方法来创建一个只有PendingIntent PendingIntent方法你可能需要。

Each method takes the current app Context, the Intent you want to wrap, and one or more flags that specify how the intent should be used (such as whether the intent can be used more than once).

每个方法使用当前应用程序上下文,意图你想包,和一个或多个标志,指定应该如何使用目的(如是否可以使用目的不止一次)。

More information about using pending intents is provided with the documentation for each of the respective use cases, such as in the Notifications and App Widgets API guides.

更多信息使用等待意图提供了文档的每个各自的用例,如通知API和应用程序部件的指南。

Intent Resolution                  意图解析


When the system receives an implicit intent to start an activity, it searches for the best activity for the intent by comparing the intent to intent filters based on three aspects:

当系统接收到一个隐式意图开始一个活动,它搜索的最佳活动意图通过比较意图过滤器是基于三个方面的目的:
目的行动

  • The intent action                  目的行动
  • The intent data (both URI and data type)                     目的数据(URI和数据类型) 
  • The intent category                 意图类别

The following sections describe how an intents are matched to the appropriate component(s) in terms of how the intent filter is declared in an app‘s manifest file.                                                                                                    接下来的章节将描述一个意图匹配到适当的组件(s)中声明的意图过滤器是如何应用程序清单文件。

Action test

To specify accepted intent actions, an intent filter can declare zero or more <action> elements. For example:

指定接受意图的行为,一个意图过滤器可以声明零个或多个<行动>元素。例如:

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

To get through this filter, the action specified in the Intent must match one of the actions listed in the filter.

通过这个过滤器,中指定的行动意图必须匹配过滤器中列出的行动之一。

If the filter does not list any actions, there is nothing for an intent to match, so all intents fail the test. However, if an Intent does not specify an action, it will pass the test (as long as the filter contains at least one action).

如果过滤器没有列出任何行动,没有什么意图相匹配,因此所有意图考试不及格。然而,如果一个意图并不指定一个行动,它将通过测试(只要过滤器包含至少一个动作)。

Category test

To specify accepted intent categories, an intent filter can declare zero or more <category> elements. For example:

指定接受意图类别,一个意图过滤器可以声明零个或多个<目录>元素。例如:

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

For an intent to pass the category test, every category in the Intent must match a category in the filter. The reverse is not necessary—the intent filter may declare more categories than are specified in the Intent and theIntent will still pass. Therefore, an intent with no categories should always pass this test, regardless of what categories are declared in the filter.

意图通过类别测试,每一个类别的意图必须匹配一个类别过滤器。反向不是必要的意图过滤器可能宣布比指定类别意图和theIntent仍将通过。因此,毫无防备的意图类别应该通过这个测试,无论什么类别中声明的过滤器。

Note: Android automatically applies the the CATEGORY_DEFAULT category to all implicit intents passed tostartActivity() and startActivityForResult(). So if you want your activity to receive implicit intents, it must include a category for "android.intent.category.DEFAULT" in its intent filters (as shown in the previous<intent-filter> example.

注意:安卓系统自动将CATEGORY_DEFAULT范畴应用到所有隐式意图通过tostartActivity()和startActivityForResult()。所以,如果你想让你的活动得到隐式意图,它必须包括一个类别为“android.intent.category.DEFAULT”其意图过滤器(如前面的< intent-filter >所示的例子。

Data test

To specify accepted intent data, an intent filter can declare zero or more <data> elements. For example:

指定接受意图的数据,一个意图过滤器可以声明零个或多个<数据>元素。例如:

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

Each <data> element can specify a URI structure and a data type (MIME media type). There are separate attributes — schemehostport, and path — for each part of the URI:

每个<数据>元素可以指定URI结构和数据类型(MIME媒体类型)。有单独的属性——计划、主机端口,和路径,为每个URI的一部分:

<scheme>://<host>:<port>/<path>

For example:    例如

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

In this URI, the scheme is content, the host is com.example.project, the port is 200, and the path isfolder/subfolder/etc.

Each of these attributes is optional in a <data> element, but there are linear dependencies:

这些属性在<数据>元素是可选的,但是有线性依赖关系:

  • If a scheme is not specified, the host is ignored.         如果没有指定一个计划,主机将被忽略。
  • If a host is not specified, the port is ignored.            如果没有指定一个主机,端口将被忽略。
  • If both the scheme and host are not specified, the path is ignored        如果不指定,计划和主机的路径将被忽略。

When the URI in an intent is compared to a URI specification in a filter, it‘s compared only to the parts of the URI included in the filter. For example:

当相比,一个意图是URI URI规范在一个过滤器,它只对部分相比URI中包含过滤器。例如:

  • If a filter specifies only a scheme, all URIs with that scheme match the filter.
  • 如果一个过滤器指定只有一个计划,所有uri方案匹配滤波器。
  • If a filter specifies a scheme and an authority but no path, all URIs with the same scheme and authority pass the filter, regardless of their paths.
  • 如果一个过滤器指定一个方案和一个权威但没有路径,所有uri相同的方案和权威通过过滤器,不管他们的路径。
  • If a filter specifies a scheme, an authority, and a path, only URIs with the same scheme, authority, and path pass the filter.
  • 如果筛选器指定了一个计划,一个权威,和一个路径,只有uri相同的方案,权威,和路径通过过滤器。

Note: A path specification can contain a wildcard asterisk (*) to require only a partial match of the path name.

注意:规范的路径可以包含通配符星号(*)只需要部分匹配的路径名。

The data test compares both the URI and the MIME type in the intent to a URI and MIME type specified in the filter. The rules are as follows:

测试的数据比较URI和MIME类型的意图过滤器中指定的URI和MIME类型。规则如下:

  1. An intent that contains neither a URI nor a MIME type passes the test only if the filter does not specify any URIs or MIME types.                                                                                                                               一个意图,其中包含一个URI和MIME类型通过测试只有在过滤不指定任何URI或MIME类型。
  2. An intent that contains a URI but no MIME type (neither explicit nor inferable from the URI) passes the test only if its URI matches the filter‘s URI format and the filter likewise does not specify a MIME type.                                                                                                                                                                                一个包含一个URI意图但没有MIME类型(既不明确也能推理的URI)通过测试只有在它的URI匹配滤波器的URI格式和过滤器同样没有指定MIME类型。
  3. An intent that contains a MIME type but not a URI passes the test only if the filter lists the same MIME type and does not specify a URI format.                                                                                                                             一个意图,包含一个MIME类型而不是一个URI通过测试只有在过滤器列表相同的MIME类型和没有指定URI的格式。
  4. An intent that contains both a URI and a MIME type (either explicit or inferable from the URI) passes the MIME type part of the test only if that type matches a type listed in the filter. It passes the URI part of the test either if its URI matches a URI in the filter or if it has a content: or file: URI and the filter does not specify a URI. In other words, a component is presumed to support content: and file: data if its filter lists only a MIME type.                                                                                                         一个意图,其中包含URI和MIME类型(显式的或能推论的URI)传递的MIME类型部分中列出的测试只有类型匹配类型的过滤器。它通过URI的一部分测试如果它的URI匹配滤波器中的一个URI或如果它有一个内容:或文件:URI和过滤器不指定一个URI。换句话说,一个组件是假定支持内容:和文件:数据如果过滤器列表只是一个MIME类型。
    最后一个规则,规则(d),反映了期望组件能够获得本地数据从文件或内容提供者。因此,他们的过滤器可以列出一个数据类型,不需要显式地名称的内容:和文件:计划。这是一个典型的案例。<数据>元素如下,例如,告诉Android,组件可以从内容提供者获取图像数据和显示:

This last rule, rule (d), reflects the expectation that components are able to get local data from a file or content provider. Therefore, their filters can list just a data type and do not need to explicitly name the content: and file:schemes. This is a typical case. A <data> element like the following, for example, tells Android that the component can get image data from a content provider and display it:

最后一个规则,规则(d),反映了期望组件能够获得本地数据从文件或内容提供者。因此,他们的过滤器可以列出一个数据类型,不需要显式地名称的内容:和文件:计划。这是一个典型的案例。<数据>元素如下,例如,告诉Android,组件可以从内容提供者获取图像数据和显示:

<intent-filter>
   
<dataandroid:mimeType="image/*"/>
    ...
</intent-filter>

Because most available data is dispensed by content providers, filters that specify a data type but not a URI are perhaps the most common.

因为大多数可用的数据是由内容提供者分配,过滤器,但不是一个URI指定一个数据类型可能是最常见的。

Another common configuration is filters with a scheme and a data type. For example, a <data> element like the following tells Android that the component can retrieve video data from the network in order to perform the action:

另一个常见的配置过滤器以一个方案和一个数据类型。例如,<数据>元素如下告诉Android,组件可以从网络获取视频数据以执行行动:

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

Intent matching

Intents are matched against intent filters not only to discover a target component to activate, but also to discover something about the set of components on the device. For example, the Home app populates the app launcher by finding all the activities with intent filters that specify the ACTION_MAIN action and CATEGORY_LAUNCHER category.

意图匹配意图过滤器不仅发现一个目标组件来激活,还发现一些关于组件的设置在设备上。例如,国内应用填充应用发射器通过寻找指定的所有活动与意图过滤器ACTION_MAIN行动和CATEGORY_LAUNCHER类别。

Your application can use intent matching in a similar way. The PackageManager has a set of query...() methods that return all components that can accept a particular intent, and a similar series of resolve...() methods that determine the best component to respond to an intent. For example, queryIntentActivities() returns a list of all activities that can perform the intent passed as an argument, and queryIntentServices() returns a similar list of services. Neither method activates the components; they just list the ones that can respond. There‘s a similar method, queryBroadcastReceivers(), for broadcast receivers.

您的应用程序可以使用意图匹配以类似的方式。PackageManager有一组查询…()方法返回所有组件,可以接受一个特定的意图,和类似的一系列解决…()方法确定最佳组件响应一个意图。例如,queryIntentActivities()返回一个列表的所有活动执行意图作为参数传递,和queryIntentServices()返回一个类似的服务列表。无论是方法激活组件;他们只是那些可以响应列表。有一个类似的方法,queryBroadcastReceivers(),为广播接收器。

API翻译 --- Intent and Intent Filters

标签:

原文地址:http://blog.csdn.net/mikky_android/article/details/51943696

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!