Android 開發中常有這樣的需求:讓使用者從圖庫挑一張圖當頭像。做法是從我們的應用去啟動系統的圖庫程式,再把結果取回來——這個介面平台早已提供。
圖庫源碼位於 android 源碼的 packages/apps 下的 gallery 資料夾。打開 AndroidManifest.xml,會看到類似這段宣告:
<activity android:name="com.android.camera.ImageGallery"
android:label="@string/gallery_label"
android:configChanges="orientation|keyboardHidden"
android:icon="@drawable/ic_launcher_gallery">
.......
<intent-filter>
<action android:name="android.intent.action.PICK" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
<data android:mimeType="video/*" />
</intent-filter>
.......
</activity>
從這個 intent-filter 可以確認:只要發出名為 android.intent.action.PICK 的 action,就能叫出圖庫並挑選圖片或影片。
要知道圖庫回傳的結果放在哪個 key,得進 com.android.camera.ImageGallery 的源碼。搜 setResult 會找到:
else {
Intent result = new Intent(null, img.fullSizeImageUri());
if (myExtras != null && myExtras.getBoolean("return-data")) {
// The size of a transaction should be below 100K.
Bitmap bitmap = img.fullSizeBitmap(IImage.UNCONSTRAINED, 100 * 1024);
if (bitmap != null) {
result.putExtra("data", bitmap);
}
}
setResult(RESULT_OK, result);
finish();
}
結論是:預設情況下, URI 直接放在 result 的 Intent data 中,可用 getData() 取得;只有當呼叫方額外傳入 return-data 為 true 時,才會把縮放後的 Bitmap 以 "data" 為 key 塞回來。實務上建議走 URI 路線,再用 ContentResolver 開啟輸入流讀圖,因為 Intent 傳 Bitmap 有大小限制(註解也明白寫著交易量應低於 100K),大圖容易引發 TransactionTooLargeException。