Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

拍照存進系統相簿卻看不到?MediaStore 插入與媒體掃描的正確做法

編輯:Android 開發實例

把圖片存進 Android 手機後,打開系統圖庫卻找不到那張圖——這是幾乎每個人都碰過的狀況。原因通常是插入後沒有通知媒體資料庫更新。先講插入本身,其實只要一行:

MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "", "");

一、insertImage 的兩個多載

這個方法帶給我第一個困擾是:無法指定照片名稱,系統會拿當前時間的毫秒數當檔名。看一下原始碼:

/**
 * 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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved