0

我想做一个像相册一样的lib并适配到Android Q中

由于 Scoped Storage,MediaStore.Images.ImageColumns.DATA不推荐使用;

我们不能像这样直接通过路径读取文件/storage/emulated/0/DCIM/xxx.png

MediaStore.Images.ImageColumns没有像 URI 这样的值,所以我无法通过 ContentProvider 获取图片。

这种方式我们只能打开一张图片(下面的代码),并且在回调中接收到一个URI;

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

// Filter to only show results that can be "opened", such as a
// file (as opposed to a list of contacts or timezones).
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Filter to show only text files.
intent.setType("image/*");

但是我想访问所有的图片,那么,如何在 Android Q 中扫描所有的图片?

4

1 回答 1

6

这就是我一直检索所有图像而不需要MediaStore.MediaColumns.DATA常量的方式

val externalUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI

val cursor = context.contentResolver
                .query(
                    externalUri,
                    arrayOf(MediaStore.MediaColumns._ID, MediaStore.MediaColumns.DATE_MODIFIED),
                    null,
                    null,
                    "${MediaStore.MediaColumns.DATE_MODIFIED} DESC"
                )

if(cursor != null){
    while(cursor.moveToNext()){
        val id = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns._ID))
        val uri = ContentUris.withAppendedId(externalUri, id.toLong())

        //do whatever you need with the uri
    }
}

cursor?.close()

它是用 Kotlin 编写的,但如果不难转换成 java

于 2019-07-19T03:52:42.470 回答