无法读取 Android 10 上的缩略图 (loadThumbnail)

Can't read thumbnails on Android 10 (loadThumbnail)

我正在使用 MediaStore.Images.Thumbnails.getThumbnail() 通过查询 MediaStore 从设备中读取缩略图。但是,这在 Android 10 (API 29) 中已被弃用,指向 ContentResolver#loadThumbnail 的指针:https://developer.android.com/reference/android/provider/MediaStore.Images.Thumbnails

但是,我无法让它工作(在模拟设备中 运行 API 29)。我已将一些 JPEG 复制到模拟设备上,这些文件最终位于“下载”文件夹中。它们在照片应用程序中显示良好。下面的代码给了我一个 FileNotFoundException。 "No content provider" 实际上告诉我什么?

try {

    Size thumbSize = new Size(100, 100);
    Uri thumbUri = Uri.fromFile(new File(imgPath));
    // imgPath: /storage/emulated/0/Download/pexels-photo-323490.jpeg
    // thumbUri: file:///storage/emulated/0/Download/pexels-photo-323490.jpeg

    Bitmap thumbBitmap;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        thumbBitmap = mContext.getContentResolver().loadThumbnail(thumbUri, thumbSize, null);
    } else {
        thumbBitmap = MediaStore.Images.Thumbnails.getThumbnail(mContext.getContentResolver(),
                imgId, MediaStore.Images.Thumbnails.MINI_KIND, null);
    }

    iconView.setImageBitmap(thumbBitmap);
} catch (Exception e) {
    Log.e("err", e.toString());
}

异常:

java.io.FileNotFoundException: No content provider: file:///storage/emulated/0/Download/pexels-photo-323490.jpeg

请试试这个,希望它对你有用:

int thumbColumn = cur.getColumnIndexOrThrow(MediaStore.Images.ImageColumns._ID); 
int _thumpId = cur.getInt(thumbColumn); 
Uri imageUri_t = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,_thumpId);

GGK

获取缩略图和所有 Android 版本的最佳答案是:

val thumbnail: Bitmap = if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)) {
    mContentResolver.loadThumbnail(contentUri, Size(width / 2, height / 2), null)
} else {
    MediaStore.Images.Thumbnails.getThumbnail(mContentResolver, id, MediaStore.Images.Thumbnails.MINI_KIND, null)
}

uri 可能不好。我的意思是尝试使用 FileProvider 获取文件的 uri。如果你的 legecyExternalStorage 是假的,那么你不能像这样访问文件。 android 12也一样,需要用MediaStore获取contentUri