就象程序可以發送數據給其他程序,所以也可以接收其他程序的數據。想一下用戶如何和程序交互,以及想從其他程序接收什么樣類型的數據。例如,一個社交程序可能對接收其他程序的文字(比如有趣的網址)感興趣。Google+ 程序可接收文字和單多張圖片。用這個app,用戶可以和容易的用Android Gallery中的相片在Google+上發布。
更新Manifest
intent filter會告訴系統程序會打算接收什么。就和前面講的如何用ACTION_SEND創建intent相似,創建intent filter來接收帶有這個操作的intent。在manifest中用<intent-filter>元素來來定義一個intent filter。例如,如果程序可接收文字,任何類型的單張圖片,或任何類型的多張圖片,mainfest應該象:
1 <activity android:name=".ui.MyActivity" > 2 <intent-filter> 3 <action android:name="android.intent.action.SEND" /> 4 <category android:name="android.intent.category.DEFAULT" /> 5 <data android:mimeType="image/*" /> 6 </intent-filter> 7 <intent-filter> 8 <action android:name="android.intent.action.SEND" /> 9 <category android:name="android.intent.category.DEFAULT" /> 10 <data android:mimeType="text/plain" /> 11 </intent-filter> 12 <intent-filter> 13 <action android:name="android.intent.action.SEND_MULTIPLE" /> 14 <category android:name="android.intent.category.DEFAULT" /> 15 <data android:mimeType="image/*" /> 16 </intent-filter> 17 </activity>
注意:更多關於intent filters和intetent解決方案請參考Intents and Intent Fileters
當其他程序通過創建intent然后傳遞給startActivity()來分享上面的類容,你的程序會在intent chooser列表中顯示,如果用戶選擇了你的程序,相應的activity(上面例子中的.ui.MyActivity)將會被啟動。然后就由你來在代碼和界面中來處理內容了。
處理傳入的數據
要處理Intent傳遞的數據,首先調用getIntent()來獲得Intent對象。一旦獲得了這個對象,可以通過查看數據來決定接下來怎么做。記住如果activity可以從系統的其他部分啟動,比如launcher,那么需要在查看intent的時候考慮這些情況。
1 void onCreate (Bundle savedInstanceState) { 2 ... 3 // 獲得 intent, action 和 MIME type 4 Intent intent = getIntent(); 5 String action = intent.getAction(); 6 String type = intent.getType(); 7 8 if (Intent.ACTION_SEND.equals(action) && type != null) { 9 if ("text/plain".equals(type)) { 10 handleSendText(intent); // 處理發送來的文字 11 } else if (type.startsWith("image/")) { 12 handleSendImage(intent); // 處理發送來的圖片 13 } 14 } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) { 15 if (type.startsWith("image/")) { 16 handleSendMultipleImages(intent); // 處理發送來的多張圖片 17 } 18 } else { 19 // 處理其他intents,比如由主屏啟動 20 } 21 ... 22 } 23 24 void handleSendText(Intent intent) { 25 String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT); 26 if (sharedText != null) { 27 // 根據分享的文字更新UI 28 } 29 } 30 31 void handleSendImage(Intent intent) { 32 Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); 33 if (imageUri != null) { 34 // 根據分享的圖片更新UI 35 } 36 } 37 38 void handleSendMultipleImages(Intent intent) { 39 ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); 40 if (imageUris != null) { 41 // 根據分享的多張圖片更新UI 42 } 43 }
注意:要格外小心的檢查傳入的數據,你不知道其他程序傳進來什么。例如,有可能設置了錯的MIME類型,或者圖片可能非常大。還要記住,在另外一個線程中處理二進制數據,而不是UI線程。
更新UI可以是像填充EditText一樣簡單,或者更難一些像在一張圖片上添加一個有趣的濾鏡。由你的程序來決定接下來會發生什么。