Android培训翻译_允许其他应用程序启动你的Activity

This lesson teaches you to

  1. Add an Intent Filter
    添加一个意图过滤器
  2. Handle the Intent in Your Activity
    在你的Activity中处理Intent
  3. Return a Result
    返回结果

You should also read

The previous two lessons focused on one side of the story: starting another app's activity from your app. But if your app can perform an action that might be useful to another app, your app should be prepared to respond to action requests from other apps. For instance, if you build a social app that can share messages or photos with the user's friends, it's in your best interest to support the ACTION_SEND intent so users can initiate a "share" action from another app and launch your app to perform the action.
前两节可专注于一件事情:从你的程序启动其他程序的activity。但是如果你的程序可以执行一个能对其它程序有用的动作,你的程序应该准备响应其它程序动作的请求。举个例子,如果你构建了一个社交程序可以让用户和朋友分享信息或照片,支持 ACTION_SEND 意图对你最为有利,这样用户可以从别的程序发起个“共享”动作,并启动你的程序来执行该动作。

 

To allow other apps to start your activity, you need to add an <intent-filter>element in your manifest file for the corresponding <activity> element.
为了让别的程序启动你的Activity,你需要添加一个<intent-filter>元素到manifest文件相应的<activity>元素下。

 

When your app is installed on a device, the system identifies your intent filters and adds the information to an internal catalog of intents supported by all installed apps. When an app calls startActivity() or startActivityForResult(), with an implicit intent, the system finds which activity (or activities) can respond to the intent.
你的程序安装到一个设备上时,系统识别出你的意图过滤器并把这个信息添加到意图的一个内部目录,这些意图被所有已安装程序支持。当一个程序用一个隐式意图调用 startActivity() 或者 startActivityFrorResult()时,系统分辨哪(几)个activy可以响应该意图。

 

Add an Intent Filter 添加一个意图过滤器


In order to properly define which intents your activity can handle, each intent filter you add should be as specific as possible in terms of the type of action and data the activity accepts.
为了正确定义哪些意图可以被你的activity处理,每个你添加的意图过滤器应当依据动作的类型和actvitiy接受的数据尽可能的具体。

 

The system may send a given Intent to an activity if that activity has an intent filter fulfills the following criteria of the Intent object:
系统可能会发送给定的Intent到一个activity ,如果那个 activity 有一个意图过滤器满足下面 Intent 对象的标准:

Action 动作
A string naming the action to perform. Usually one of the platform-defined values such as ACTION_SEND or ACTION_VIEW.
一个字符串命名的动作执行。通常是平台定义的一个值,例如:ACTION_SEND 或者 ACTION_VIEW。
Specify this in your intent filter with the <action> element. The value you specify in this element must be the full string name for the action, instead of the API constant (see the examples below).
用 <action> 标签在你的意图过滤器中指定。这个标签中指定的值必须是动作的全字符串名,而不是API常数(见下面的例子)
 
Data 数据
A description of the data associated with the intent.
与意图关联的数据的描述。
Specify this in your intent filter with the <data>element. Using one or more attributes in this element, you can specify just the MIME type, just a URI prefix, just a URI scheme, or a combination of these and others that indicate the data type accepted.
用<data>标签在你的意图过滤器中指定。这个标签使用一到多个属性,你可以指定MIME类型,URI 前缀,URI 计划,或者这些和其它可用数据类型的组合。

 

Note: If you don't need to declare specifics about the dataUri (such as when your activity handles to other kind of "extra" data, instead of a URI), you should specify only the android:mimeType attribute to declare the type of data your activity handles, such as text/plain or image/jpeg.
:如果你不需要声明有关数据Uri的细节(例如,你activity处理其它类型的extra数据,而不是URI时),你应当唯一指明 android:mimeType 属性声明你activity处理的数据类型,例如 text/plain 或者 image/jpeg。

 

Category 分类
Provides an additional way to characterize the activity handling the intent, usually related to the user gesture or location from which it's started. There are several different categories supported by the system, but most are rarely used. However, all implicit intents are defined withCATEGORY_DEFAULTby default.
提供一个额外的方法描述activity处理意图的特征, 常常与用户手势或其启动的位置有关。系统支持几种不同的类别,但是大多数很少使用。然而,所有的隐式意图默认都是用CATEGORY_DEFAULT定义的。
 
Specify this in your intent filter with the <category>element.
用<category>标签在你的意图过滤器中指定。

In your intent filter, you can declare which criteria your activity accepts by declaring each of them with corresponding XML elements nested in the <intent-filter>element.
在你的意图过滤器中,你可以声明你的activity 接受的标准,在<intent-filter> 标签中声明每个对象相应的xml元素。

 

For example, here's an activity with an intent filter that handles the ACTION_SEND intent when the data type is either text or an image:
例如下面的activity,当数据类型为文本或图像时,使用意图过滤器处理 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"/>
        <data android:mimeType="image/*"/>
    </intent-filter>
</activity>

 

Each incoming intent specifies only one action and one data type, but it's OK to declare multiple instances of the <action>, <category>, and <data> elements in each<intent-filter>.
每个传入的意图仅指定一个动作和一个数据类型,但是每个<intent-filter>中声明多个<action>,<category>和<date>元素也是没问题的。

 

If any two pairs of action and data are mutually exclusive in their behaviors, you should create separate intent filters to specify which actions are acceptable when paired with which data types.
如果任意两对动作和数据在他们的行为中是相互排斥的,你应当创建独立的意图过滤器去指定那些动作可以接受与哪些数据类型配对。

 

For example, suppose your activity handles both text and images for both the ACTION_SEND and ACTION_SENDTO intents. In this case, you must define two separate intent filters for the two actions because a ACTION_SENDTO intent must use the data Uri to specify the recipient's address using the send or sendto URI scheme. For example:
假设你的activity 为ACION_SEND和ACTION_SENDTO 意图处理文字和图像。这个例子中,你必须单独为两个动作定义两个意图过滤器,因为一个ACTION_SENDTO意图必须通过send或者sendto URI计划使用Uri数据指定接收者的地址。如下:

<activity android:name="ShareActivity">
    <!-- filter for sending text; accepts SENDTO action with sms URI schemes 发送文本的过滤器;用sms URI 计划接受SENDTO动作 -->
    <intent-filter>
        <action android:name="android.intent.action.SENDTO"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:scheme="sms" />
        <data android:scheme="smsto" />
    </intent-filter>
    <!-- filter for sending text or images; accepts SEND action and text or image data 发送文本或图片过滤器;接受SEND动作和文本或者图片数据 -->
    <intent-filter>
        <action android:name="android.intent.action.SEND"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:mimeType="image/*"/>
        <data android:mimeType="text/plain"/>
    </intent-filter>
</activity>

 

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

:为了获取隐式意图,你必须在意图过滤器中包含CATEGORY_DEFAULT 类别。startActivity()和startActivityForResult()方法对待所有意图就像他们包含了CATEGORY_DEFAULT类别一样。如果你不想声明它,你的activity将检索不到任何的隐式意图。

 

For more information about sending and receiving ACTION_SENDintents that perform social sharing behaviors, see the lesson about Receiving Content from Other Apps.
更多关于发送和接收 ACTION_SEND 意图执行社交分享行为的信息,请参见课程 从其它程序接收内容。

 

Handle the Intent in Your Activity
在你的Activity中处理意图


In order to decide what action to take in your activity, you can read the Intent that was used to start it.
为了决定在你的activty中获得什么动作,你可以阅读Intent,用来启动activity。

 

As your activity starts, call getIntent() to retrieve theIntent that started the activity. You can do so at any time during the lifecycle of the activity, but you should generally do so during early callbacks such asonCreate() or onStart().
因为你activity启动,调用getIntent()来获取启动该activity的意图。你可以在该activity声明周期的任意时刻这么做,但是你应该通常在回调的早起这么做,例如 onCreate() 或者 onStart()。

 

For example: 示例

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    // Get the intent that started this activity 
    // 获取启动了该activity的意图
    Intent intent = getIntent();
    Uri data = intent.getData();

    // Figure out what to do based on the intent type 
    // 弄明白基于这个意图类型可以做什么
    if (intent.getType().indexOf("image/") != -1) {
        // Handle intents with image data ... 
        // 用图像数据处理意图...
    } else if (intent.getType().equals("text/plain")) {
        // Handle intents with text ... 
        // 用文本处理意图...
    }
}

 

Return a Result
返回结果


If you want to return a result to the activity that invoked yours, simply call setResult() to specify the result code and result Intent. When your operation is done and the user should return to the original activity, call finish() to close (and destroy) your activity. For example:
如果你想向调用你的activity返回结果,只需调用 setResult() 去指定结果代码和结果意图。当你的操作完成并且用户想要返回之前的activity时,调用 finish() 关闭(并摧毁)你的activity。例如:

// Create intent to deliver some kind of result data
// 创建意图传送一些结果数据
Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("content://result_uri");
setResult(Activity.RESULT_OK, result);
finish();

 

You must always specify a result code with the result. Generally, it's either RESULT_OK or RESULT_CANCELED. You can then provide additional data with an Intent, as necessary.
你必须总是指定结果的结果代码。一般来讲,是RESULT_OK 或是RESULT_CANCELED。有必要的话,你之后可以用意图提供额外的数据。

 

Note: The result is set to RESULT_CANCELED by default. So, if the user presses the Backbutton before completing the action and before you set the result, the original activity receives the "canceled" result.

:默认情况下结果被设置为 RESULT_CANCELED。因此,如果用户在完成动作和你设置结果前按了回退按钮,原先的activity会获得“被取消”结果。

 

If you simply need to return an integer that indicates one of several result options, you can set the result code to any value higher than 0. If you use the result code to deliver an integer and you have no need to include the Intent, you can call setResult() and pass only a result code. For example:
如果你只是需要返回一个整数,指出几种结果选项之一,你可以设置返回码为任何大于0的值。如果你使用结果代码传送一个整数而不需要包括意图,你可以调用 setResult() 仅传送一个结果代码。

setResult(RESULT_COLOR_RED);
finish();

 

In this case, there might be only a handful of possible results, so the result code is a locally defined integer (greater than 0). This works well when you're returning a result to an activity in your own app, because the activity that receives the result can reference the public constant to determine the value of the result code.
这个例子中,可能只有几个可能的结果,因此返回码是个本地定义的整数(大于0)。你在自己的应用中返回一个结果到一个activity时这种方式很管用,因为获取结果的activity可以引用公共常量来决定结果码的值。

 

Note: There's no need to check whether your activity was started with startActivity() or startActivityForResult(). Simply call setResult() if the intent that started your activity might expect a result. If the originating activity had called startActivityForResult(), then the system delivers it the result you supply to setResult(); otherwise, the result is ignored.

:没必要去检查你的activity是用 startActivity() 还是 startActivityForResult() 启动的。 如果启动你activity的意图可能期待一个结果,简单调用setResult()便好。如果原始的activity已经调用了 startActivityForResult() ,那么系统会传送你提供的结果到setResult(),否则结果就会被忽略。

posted on 2012-08-21 16:49  梵谷星辰  阅读(1494)  评论(0编辑  收藏  举报

导航