Android官方开发文档Training系列课程中文版:分享简单数据之从其它APP接收简单数据
原文地址:http://android.xsoftlab.net/training/sharing/receive.html
正如你的程序可以發送數據給其它程序,那么你也可以輕松的接收數據。想象一下用戶如何與你的程序交互,以及你想從其它應用程序接收的數據類型。舉個例子,一個社交網絡的程序可能對文本內容更感興趣,比如一個有意思的Web地址,Google+ APP允許接收文本、單張圖片或者多張圖片。通過這個APP,用戶可以很輕松的從Android圖庫APP啟動一個Google+的發送照片任務。
更新你的清單文件
意圖過濾器告知系統可以接收什么樣的意圖。舉個例子,如果應用程序可以接收并處理文本內容,和任何類型的一張圖片,或者任何類型的多張圖片,你的清單文件應該聲明成這樣:
<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:有關更多意圖過濾器的信息以及意圖的分辨,請閱讀: Intents and Intent Filters
當另一個程序通過構造一個意圖并且傳遞給startActivity()并嘗試分享這幾種類型的任意一種時,你的程序會在意圖選擇器中列出各種選項。如果用戶選擇了你的程序,那么相應的activity會被啟動。然后由你的代碼和UI來妥善的處理這些內容。
處理到來的內容
為了處理由Intent傳遞過來的內容,開始調用getIntent()方法獲得Intent對象。一旦你獲得了這個對象,你可以檢查其中的內容然后在決定接下來怎么做。記住一點,如果這個activity可以由系統的其它部分啟動,比如系統的桌面,然后你需要在執行檢查的時候將這種情況考慮在內。
void onCreate (Bundle savedInstanceState) {...// Get intent, action and MIME typeIntent 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:檢查到來的附加數據要格外當心,你永遠不會知道其它應用程序會發來什么。舉個例子,比如可能設置了錯誤的MIME類型,或者發送來的圖像可能非常的大。還要記得要在單獨的線程中處理二進制數據,而不是主線程。
更新UI可以像填充一個EditText一樣簡單,否則的話它會像對圖片應用有趣圖片過濾器一樣復雜,這需要您的應用程序明確接下來將要做什么。
總結
以上是生活随笔為你收集整理的Android官方开发文档Training系列课程中文版:分享简单数据之从其它APP接收简单数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 从源码的角度说说Activity的set
- 下一篇: Android官方开发文档Trainin