Android doc译文|Building Apps with Content Sharing|Sharing Simple Data

来源:互联网 发布:淘宝店名logo在线设计 编辑:程序博客网 时间:2024/05/19 12:38

Sharing Simple Data

One of the great things about Android applications is their ability to communicate and integrate with each other. Why reinvent functionality that isn’t core to your application when it already exists in another application?
Android应用程序的一个最棒的事是它们和其他apk的通信能力。为什么要重复复制一个其他应用程序已经存在的,并不是你app的核心功能?

This class covers some common ways you can send and receive simple data between applications using Intent APIs and the ActionProvider object.
这节课包含了几个通常的方法:你可以在Android应用程序之间,使用意图API和ActionProvider发送或者接受简单的数据.

Sending Simple Data to Other Apps(使用intent分享数据)

When you construct an intent, you must specify the action you want the intent to “trigger.” Android defines several actions, including ACTION_SEND which, as you can probably guess, indicates that the intent is sending data from one activity to another, even across process boundaries. To send data to another activity, all you need to do is specify the data and its type, the system will identify compatible receiving activities and display them to the user (if there are multiple options) or immediately start the activity (if there is only one option). Similarly, you can advertise the data types that your activities support receiving from other applications by specifying them in your manifest.
当你构造一个intent的时候,你必须指定你希望intent被什么action所“触发”。Android定义了几个actions,包括ACTION_SEND:当你暗示或表明是从一个Activity发送数据到其他Activity,甚至数跨进程的。为了发送数据到其他Activity,你需要做的是定义数据和数据类型,系统会识别可以接收和处理的Activities,并且把这些应用都呈现给用户看(如果没有默认选项)会在直接打开Activity(如果只有一个选项)。类似的,你可以在清单文件中定义你的Activity可以从其他Activity接收的数据类型。
Sending and receiving data between applications with intents is most commonly used for social sharing of content. Intents allow users to share information quickly and easily, using their favorite applications.
对于社交软件内容分享来说,用意图在应用程序之间发送和接收数据,是最常用的。Intents允许用户轻松快捷地使用他们喜欢的应用程序分享信息。

Note: The best way to add a share action item to an ActionBar is to use ShareActionProvider, which became available in API level 14. ShareActionProvider is discussed in the lesson about Adding an Easy Share Action.
注意:新增一个分享动作item到ActionBar的最好的方式是使用ShareActionProvider控件,这在Android API 14被支持。ShareActionProvider在Adding an Easy Share Action一节会被讨论。

Send Text Content
这里写图片描述
Figure 1. Screenshot of ACTION_SEND intent chooser on a handset.
手机上的ACTION_SEND 意图选择截图
The most straightforward and common use of the ACTION_SEND action is sending text content from one activity to another. For example, the built-in Browser app can share the URL of the currently-displayed page as text with any application. This is useful for sharing an article or website with friends via email or social networking. Here is the code to implement this type of sharing:
使用ACTION_SEND 最直接和最通常的方法是从一个Activity向另一个Activity发送文本内容。比如,一个内置的浏览器可以以文本的形式分享当前浏览器正在显示的网页地址给任意app。对于和朋友分享文章或者网站是非常有用的。这里是这种分享方式的实现。

Intent sendIntent = new Intent();sendIntent.setAction(Intent.ACTION_SEND);sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");sendIntent.setType("text/plain");startActivity(sendIntent);

If there’s an installed application with a filter that matches ACTION_SEND and MIME type text/plain, the Android system will run it; if more than one application matches, the system displays a disambiguation dialog (a “chooser”) that allows the user to choose an app.
如果手机上已经安装了一个应用程序,其意图过滤器(intent-filter)与ACTION_SEND 以及MIME type text/plain匹配,系统就会运行这个应用程序;如果有多个Application匹配,系统会显示一个对话框让用户选择一个应用程序。
However, if you call Intent.createChooser(), passing it your Intent object, it returns a version of your intent that will always display the chooser. This has some advantages:
然而,如果你调用了Intent.createChooser并向他传递可你的Intent对象,它会返回一个你指定的version的intent对象,并且每次都会调起这个对话框。这有几个好处:

  • Even if the user has previously selected a default action for this
    intent, the chooser will still be displayed.
  • If no applications match, Android displays a system message.
  • You can specify a title for the chooser dialog.
  • 即使用户之前选择了一个默认的动作,这个对话框仍然每次都会启动。
  • 如果没有匹配的应用程序,Android会发送一个系统信息。
  • 你可以稍稍修改这个对话框。

Here’s the updated code:
以下是更新后的代码:

Intent sendIntent = new Intent();sendIntent.setAction(Intent.ACTION_SEND);sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");sendIntent.setType("text/plain");startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));

The resulting dialog is shown in figure 1.
这个对话框在图一显示。

Optionally, you can set some standard extras for the intent: EXTRA_EMAIL, EXTRA_CC, EXTRA_BCC, EXTRA_SUBJECT. If the receiving application is not designed to use them, it simply ignores them.
或者你可以为intent设置一些规定之外的一些参数:EXTRA_EMAIL, EXTRA_CC, EXTRA_BCC, EXTRA_SUBJECT。如果接受的应用程序没有被设计来匹配这些参数,这些app就会被直接忽略。

Note: Some e-mail applications, such as Gmail, expect a String[] for extras like EXTRA_EMAIL and EXTRA_CC, use putExtra(String, String[]) to add these to your intent.
注意:一些邮件app比如Gmail,期望一个额外的String数组,比如EXTRA_EMAIL and EXTRA_CC,你可以用putExtra(String, String[])来添加参数到intent。

Send Binary Content
Binary data is shared using the ACTION_SEND action combined with setting the appropriate MIME type and placing the URI to the data in an extra named EXTRA_STREAM. This is commonly used to share an image but can be used to share any type of binary content:
二进制数据可以被分享前提是同时满足3个条件:使用ACTION_SEND action,设置适当的MIME类型,在一个叫做EXTRA_STREAM的额外数据放置URI。这通常被用于分享一个图片,但是这种方法其实可以分享任意的二进制数据文件。

Intent shareIntent = new Intent();shareIntent.setAction(Intent.ACTION_SEND);shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);shareIntent.setType("image/jpeg");startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));

Note the following:
注意以下:

You can use a MIME type of “* /*”, but this will only match activities that are able to handle generic data streams.
The receiving application needs permission to access the data the Uri points to. The recommended ways to do this are:
你可以使用一个MIME类型的”* /*”,但是这只能匹配那些能够处理一般数据流的Activity。接受的应用程序需要访问data中的Uri指向的资源的权限。推荐的方式是:
Store the data in your own ContentProvider, making sure that other apps have the correct permission to access your provider. The preferred mechanism for providing access is to use per-URI permissions which are temporary and only grant access to the receiving application. An easy way to create a ContentProvider like this is to use the FileProvider helper class.
在你自己的ContentProvider储存数据,确认其他app有正确的权限来访问你的provider(提供者)。对于提供权限,推荐的机制是使用预URI权限,这只是一个临时权限仅仅在接受方应用程序有效。一个创建ContentProvider的简单方法是使用FileProvider helper类。
Use the system MediaStore. The MediaStore is primarily aimed at video, audio and image MIME types, however beginning with Android 3.0 (API level 11) it can also store non-media types (see MediaStore.Files for more info). Files can be inserted into the MediaStore using scanFile() after which a content:// style Uri suitable for sharing is passed to the provided onScanCompleted() callback. Note that once added to the system MediaStore the content is accessible to any app on the device.
使用系统的MediaStore。MediaStore倾向于视频,音频以及MIME类型是图片的数据,然而,在Android3.0开始,Android也支持存储非媒体类型的数据类型了(更多信息参见MediaStore.Files)。使用scanFile()文件可以被插入到MediaStore 之后一个适合用来分享的“content://”形式的Uri 被传递给onScanCompleted()回调。注意,一旦数据加入了系统MediaStore,所有app都可以访问。
Send Multiple Pieces of Content
To share multiple pieces of content, use the ACTION_SEND_MULTIPLE action together with a list of URIs pointing to the content. The MIME type varies according to the mix of content you’re sharing. For example, if you share 3 JPEG images, the type is still “image/jpeg”. For a mixture of image types, it should be ”image/ * ”to match an activity that handles any type of image. You should only use “* /*” if you’re sharing out a wide variety of types. As previously stated, it’s up to the receiving application to parse and process your data. Here’s an example:
要分享几条信息,使用ACTION_SEND_MULTIPLE action,并且用一个Uri的list指向content。MIME类型根据你分享的内容的混杂程度而不同。比如,如果你的分享了一个3 JPEG的图片,type仍然是”image/jpeg”。对于一个混杂的图片类型,应该是“”image/” ”,以匹配一个可以处理任何图片类型的app。如果你要分享多种类型的数据你应该使用” / *”。就如之前提到的,这取决于接受的app怎么解析你的数据。以下是例子

ArrayList<Uri> imageUris = new ArrayList<Uri>();imageUris.add(imageUri1); // Add your image URIs hereimageUris.add(imageUri2);Intent shareIntent = new Intent();shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);shareIntent.setType("image/*");startActivity(Intent.createChooser(shareIntent, "Share images to.."));

As before, make sure the provided URIs point to data that a receiving application can access.
像以前一样,确认提供的URI指向的数据,接受的app要能够访问。

Receiving Simple Data from Other Apps

Just as your application can send data to other applications, so too can it easily receive data from applications. Think about how users interact with your application, and what data types you want to receive from other applications. For example, a social networking application would likely be interested in receiving text content, like an interesting web URL, from another app. The Google+ Android application accepts both text and single or multiple images. With this app, a user can easily start a new Google+ post with photos from the Android Gallery app.
就如你的app可以向其他app发送数据,其他app也可以简单地从其他应用程序接受数据。需要考虑用户如何可以打断你的app,以及你的app期待的数据类型。比如,一个网络社交app应该会对文本数据类型感兴趣,比如来自其他app的一个网址。Google+ Android应用程序接受文本和多种图片类型。有这个app,用户可以轻易的从Android图库app发起一个Google+打开请求。

Update Your Manifest
Intent filters inform the system what intents an application component is willing to accept. Similar to how you constructed an intent with action ACTION_SEND in the Sending Simple Data to Other Apps lesson, you create intent filters in order to be able to receive intents with this action. You define an intent filter in your manifest, using the <intent-filter> element. For example, if your application handles receiving text content, a single image of any type, or multiple images of any type, your manifest would look like:
Intent filters会告诉系统什么app接受什么样的数据类型。类似在“Sending Simple Data to Other Apps ”一课中,你如何使用action ACTION_SEND构建一个intent,你创建一个意图过滤器,目的是能够接受是这种action的intent。你可以在清单文件用<intent-filter> 定义一个意图过滤器。比如,如果你的app处理文本内容,一系列类型的图片,你的清单文件应该如下:

<activity android:name=".ui.MyActivity" >    <intent-filter>        <action android:name="android.intent.action.SEND" />        <category android:name="android.intent.category.DEFAULT" />        <data android:mimeType="image/*" />    </intent-filter>    <intent-filter>        <action android:name="android.intent.action.SEND" />        <category android:name="android.intent.category.DEFAULT" />        <data android:mimeType="text/plain" />    </intent-filter>    <intent-filter>        <action android:name="android.intent.action.SEND_MULTIPLE" />        <category android:name="android.intent.category.DEFAULT" />        <data android:mimeType="image/*" />    </intent-filter></activity>

Note: For more information on intent filters and intent resolution please read Intents and Intent Filters
注意:关于intent filters 和 intent resolution的更多信息参见Intents and Intent Filters

When another application tries to share any of these things by constructing an intent and passing it to startActivity(), your application will be listed as an option in the intent chooser. If the user selects your application, the corresponding activity (.ui.MyActivity in the example above) will be started. It is then up to you to handle the content appropriately within your code and UI.
当另一个app尝试构建一个intent,并把它传进startActivity(),以分享这些类型的数据时你的app将会被列在 intent chooser作为一个选项。如果用户选择了你的app,响应Activity(例子中是.ui.MyActivity)就会启动,之后就取决于你怎么在你的UI和代码中处理数据了。

Handle the Incoming Content
To handle the content delivered by an Intent, start by calling getIntent() to get Intent object. Once you have the object, you can examine its contents to determine what to do next. Keep in mind that if this activity can be started from other parts of the system, such as the launcher, then you will need to take this into consideration when examining the intent.
为了处理intent传递来的内容,可以调用getIntent()来获得Intent对象。一旦你拥有了intent对象,你可以检查它的内容并决定接下来做什么。记住activity有可能被系统的其他部分启动起来,比如launcher,那么你就需要在测试intent的时候把这个情况考虑进去。

void onCreate (Bundle savedInstanceState) {    ...    // Get intent, action and MIME type    Intent intent = getIntent();    String action = intent.getAction();    String type = intent.getType();    if (Intent.ACTION_SEND.equals(action) && type != null) {        if ("text/plain".equals(type)) {            handleSendText(intent); // Handle text being sent        } else if (type.startsWith("image/")) {            handleSendImage(intent); // Handle single image being sent        }    } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {        if (type.startsWith("image/")) {            handleSendMultipleImages(intent); // Handle multiple images being sent        }    } else {        // Handle other intents, such as being started from the home screen    }    ...}void handleSendText(Intent intent) {    String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);    if (sharedText != null) {        // Update UI to reflect text being shared    }}void handleSendImage(Intent intent) {    Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);    if (imageUri != null) {        // Update UI to reflect image being shared    }}void handleSendMultipleImages(Intent intent) {    ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);    if (imageUris != null) {        // Update UI to reflect multiple images being shared    }}

Caution: Take extra care to check the incoming data, you never know what some other application may send you. For example, the wrong MIME type might be set, or the image being sent might be extremely large. Also, remember to process binary data in a separate thread rather than the main (“UI”) thread.
注意:多留心,检查接收的数据,你不会知道其他app会发送什么样的数据给你。比如,错误的MIME类型,或者,传递的图片非常大。也要记住处理二进制数据要放在单独的线程而不是主(UI)线程。

Updating the UI can be as simple as populating an EditText, or it can be more complicated like applying an interesting photo filter to an image. It’s really specific to your application what happens next.
更新UI可以简单到只是填充一个EditText,或者可能很复杂,比如应用一个有趣的图片过滤器到一个图片。这就取决于你的app了。

Adding an Easy Share Action(未完待续————–翻译了一点Android文档发现工作后一些Java和Android的知识竟然遗忘了,所以暂时不打算翻译文档了,从头复习一下Java的一些知识,此坑待填——————————-)

Implementing an effective and user friendly share action in your ActionBar is made even easier with the introduction of ActionProvider in Android 4.0 (API Level 14). An ActionProvider, once attached to a menu item in the action bar, handles both the appearance and behavior of that item. In the case of ShareActionProvider, you provide a share intent and it does the rest.
在你的ActionBar实现一个有效的和用户友好的分享动作甚至比在Android4.0的ActionProvider 更简单。ActionProvider,一旦把一个菜单项添加到一个ActionProvider,

Note: ShareActionProvider is available starting with API Level 14 and higher.

Figure 1. The ShareActionProvider in the Gallery app.

Update Menu Declarations
To get started with ShareActionProviders, define the android:actionProviderClass attribute for the corresponding in your menu resource file:


0 0
原创粉丝点击