Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android doc譯文|Building Apps with Content Sharing|Sharing Simple Data

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

編輯:關於Android編程

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 choZ喎?/kf/ware/vc/" target="_blank" class="keylink">vc2VyIG9uIGEgaGFuZHNldC48YnIgLz4NCsrWu/rJz7XEQUNUSU9OX1NFTkQg0uLNvNGh1PG92M28PGJyIC8+DQpUaGUgbW9zdCBzdHJhaWdodGZvcndhcmQgYW5kIGNvbW1vbiB1c2Ugb2YgdGhlIEFDVElPTl9TRU5EIGFjdGlvbiBpcyBzZW5kaW5nIHRleHQgY29udGVudCBmcm9tIG9uZSBhY3Rpdml0eSB0byBhbm90aGVyLiBGb3IgZXhhbXBsZSwgdGhlIGJ1aWx0LWluIEJyb3dzZXIgYXBwIGNhbiBzaGFyZSB0aGUgVVJMIG9mIHRoZSBjdXJyZW50bHktZGlzcGxheWVkIHBhZ2UgYXMgdGV4dCB3aXRoIGFueSBhcHBsaWNhdGlvbi4gVGhpcyBpcyB1c2VmdWwgZm9yIHNoYXJpbmcgYW4gYXJ0aWNsZSBvciB3ZWJzaXRlIHdpdGggZnJpZW5kcyB2aWEgZW1haWwgb3Igc29jaWFsIG5ldHdvcmtpbmcuIEhlcmUgaXMgdGhlIGNvZGUgdG8gaW1wbGVtZW50IHRoaXMgdHlwZSBvZiBzaGFyaW5nOjxiciAvPg0KyrnTw0FDVElPTl9TRU5EINfu1rG907rN1+7NqLOjtcS3vbeoyse009K7uPZBY3Rpdml0ec/ywe3Su7j2QWN0aXZpdHm3osvNzsSxvsTayN2ho7HIyOejrNK7uPbE2tbDtcTkr8DAxve/ydLU0tTOxLG+tcTQzsq9t9bP7bWxx7Dkr8DAxvfV/dTaz9TKvrXEzfjSs7XY1re4+MjO0uJhcHCho7bU09q6zcXz09G31s/tzsTVwrvy1d/N+NW+yse3x7Oj09DTw7XEoaPV4sDvysfV4tbWt9bP7be9yr21xMq1z9ahozwvcD4NCjxwcmUgY2xhc3M9"brush:java;"> 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 imageUris = new ArrayList();
imageUris.add(imageUri1); // Add your image URIs here
imageUris.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 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。你可以在清單文件用 定義一個意圖過濾器。比如,如果你的app處理文本內容,一系列類型的圖片,你的清單文件應該如下:


    
        
        
        
    
    
        
        
        
    
    
        
        
        
    

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 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(未完待續—)

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:

 

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved