編輯:Android 開發實例
把圖片存進 Android 手機後,打開系統圖庫卻找不到那張圖——這是幾乎每個人都碰過的狀況。原因通常是插入後沒有通知媒體資料庫更新。先講插入本身,其實只要一行:
MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "", "");
這個方法帶給我第一個困擾是:無法指定照片名稱,系統會拿當前時間的毫秒數當檔名。看一下原始碼:
/**
* Insert an image and create a thumbnail for it.
*
* @param cr The content resolver to use
* @param source The stream to use for the image
* @param title The name of the image
* @param description The description of the image
* @return The URL to the newly created image, or null if the image failed
* to be stored for any reason.
*/
public static final String insertImage(ContentResolver cr, Bitmap source,
String title, String description) {
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, title);
values.put(Images.Media.DESCRIPTION, description);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri url = null;
String stringUrl = null; /* value to be returned */
try {
url = cr.insert(EXTERNAL_CONTENT_URI, values);
if (source != null) {
OutputStream imageOut = cr.openOutputStream(url);
try {
source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
} finally {
imageOut.close();
}
long id = ContentUris.parseId(url);
// Wait until MINI_KIND thumbnail is generated.
Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id,
Images.Thumbnails.MINI_KIND, null);
// This is for backward compatibility.
Bitmap microThumb = StoreThumbnail(cr, miniThumb, id, 50F, 50F,
Images.Thumbnails.MICRO_KIND);
} else {
Log.e(TAG, "Failed to create thumbnail, removing original");
cr.delete(url, null, null);
url = null;
}
} catch (Exception e) {
Log.e(TAG, "Failed to insert image", e);
if (url != null) {
cr.delete(url, null, null);
url = null;
}
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
}
我以為 title 就是圖片名稱,設定之後卻沒有效果,於是繼續往下挖,發現另一個多載:
/**
* Insert an image and create a thumbnail for it.
*
* @param cr The content resolver to use
* @param imagePath The path to the image to insert
* @param name The name of the image
* @param description The description of the image
* @return The URL to the newly created image
* @throws FileNotFoundException
*/
public static final String insertImage(ContentResolver cr, String imagePath,
String name, String description) throws FileNotFoundException {
// Check if file exists with a FileInputStream
FileInputStream stream = new FileInputStream(imagePath);
try {
Bitmap bm = BitmapFactory.decodeFile(imagePath);
String ret = insertImage(cr, bm, name, description);
bm.recycle();
return ret;
} finally {
try {
stream.close();
} catch (IOException e) {
}
}
}
結果這個方法只是回頭呼叫第一個,name 就是傳進去的 title。也就是說,關鍵不在 API 而在資料庫欄位本身:TITLE 並不是檔案名稱,檔名存在 DISPLAY_NAME 或系統實際的 _display_name 欄位裡,而 insertImage() 從頭到尾都沒有寫入它,於是 MediaProvider 只能退回用時間戳補上。
真正可控的做法是自己組 ContentValues 插入,把 DISPLAY_NAME、MIME_TYPE 與 DATE_ADDED 一併寫入,再透過 openOutputStream 寫入位元資料。
資料寫進去了,圖庫仍可能因為索引未更新而看不到。最直白的做法是發送全域掃描廣播:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
但這條廣播會掃描整張 SD 卡。卡裡東西一多就掃很久,而掃描期間無法存取 SD 卡,使用者體驗很差。用過微信就知道,它存檔案後並不會掃描整張卡。更好的方式是只針對單一檔案:
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(new File("/sdcard/image.jpg"));
intent.setData(uri);
mContext.sendBroadcast(intent);
或者用 MediaScannerConnection:
final MediaScannerConnection msc = new MediaScannerConnection(mContext,
new MediaScannerConnectionClient() {
public void onMediaScannerConnected() {
msc.scanFile("/sdcard/image.jpg", "image/jpeg");
}
public void onScanCompleted(String path, Uri uri) {
Log.v(TAG, "scan completed");
msc.disconnect();
}
});
insertImage(cr, source, title, description) 回傳的就是插入後的 Uri,由它反查絕對路徑即可:
private String getFilePathByContentResolver(Context context, Uri uri) {
if (null == uri) {
return null;
}
Cursor c = context.getContentResolver().query(uri, null, null, null, null);
String filePath = null;
if (null == c) {
throw new IllegalArgumentException(
"Query on " + uri + " returns null result.");
}
try {
if ((c.getCount() != 1) || !c.moveToFirst()) {
} else {
filePath = c.getString(
c.getColumnIndexOrThrow(MediaColumns.DATA));
}
} finally {
c.close();
}
return filePath;
}
有了絕對路徑,就能只針對單一檔案觸發掃描,不必再發送掃描整張卡的廣播。
上面這套寫法屬於直接操作 SD 卡路徑的舊模式。從 Android 4.4 起,公開應用已不建議再拼 /sdcard/... 硬編碼路徑;Android 10 導入分區儲存(Scoped Storage)後,WRITE_EXTERNAL_STORAGE 對多數 App 已不再適用,而 MediaColumns.DATA 也已被標記為廢棄。
現行的標準做法是:用 MediaStore.Images.Media.insertAsync()(API 30+)或自行組 ContentValues 插入到 MediaStore,透過 ContentResolver.openOutputStream(uri) 寫入圖片,設定 IS_PENDING 為 0 完成發布——這個流程會自動觸發媒體索引,不需要手動發廣播。若要拍攝照片,則用 FileProvider 建立內容 URI 交給 ACTION_IMAGE_CAPTURE,回傳後同樣只需更新 IS_PENDING。
Android記事本範例剖析(一):入口、清單與 Intent 匹配機制
這是 Android 記事本範例系列的第一篇。與其直接背誦 API,不如從一個完整的小程式開始,觀察入口、列表、Intent 與 ContentProvider 如何串起
Android MediaPlayer:打造自己的音樂播放器
Android 在音訊與影片播放上提供了相當完整的支援,而其中最常被直接使用的一條路徑,就是 MediaPlayer 這個類別。它被封裝在 android.media 套
Android 接入新浪微博、騰訊微博與人人網的 OAuth 2.0 實作
許多 Android 應用會需要接入社交平台的分享、登入或發文能力。本文以新浪微博、騰訊微博與人人網為例,說明整合時最關鍵的授權流程,以及如何取得後續呼叫 API 所需的
用 ViewPager 打造自動輪播廣告板:完整源碼分享
android-support-v4.jar 是 Google 官方為相容低版本裝置所提供的套件,裡面包含了原本只有 Android 3.0 以上才支援的 API,而 V