如何在 Android 中使用 ContentResolver 在自定义文件夹中查询 images/videos?

How query images/videos in custom folders using ContentResolver in Android?

我在 Pictures 目录中有一个自定义文件夹,例如 Pictures/MyFolder。它在 MyFolder 中有图像。以下是仅在 MyFolder 文件夹上使用 ContentResolver 查询图像的方法。

我试过了

Cursor mediaCursor = context.getContentResolver().query(
                MediaStore.Files.getContentUri("external"),
                null,
                MediaStore.MediaColumns.RELATIVE_PATH + " like ? ",
                new String[]{"%MyFolder%"},
                null);

但它还包含其他文件。还是内容解析器的替代品?

您可以使用以下函数从文件夹中获取图像。

private void getImageFolderList() {
    String[] projection = new String[] { MediaStore.Images.Media.DATA,
                    MediaStore.Images.Media._ID,
                    MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
                    MediaStore.Images.Media.DATE_TAKEN };
            Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
            Cursor cur = getContentResolver().query(images, projection, // Which
                                                                        // columns
                                                                        // to return
                    null, // Which rows to return (all rows)
                    null, // Selection arguments (none)
                    orderBy + " DESC" // Ordering
            );
            ArrayList<String> imagePath;
            if (cur.moveToFirst()) {
                String bucket, date;
                int bucketColumn = cur.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
                int dateColumn = cur.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN);
                do {
                    bucket = cur.getString(bucketColumn);
                    date = cur.getString(dateColumn);
                    if (!allFolder.contains(bucket)) {
                        allFolder.add(bucket);
                    }
                    imagePath = listImageByFolder.get(bucket);
                    if (imagePath == null) {
                        imagePath = new ArrayList<String>();
                    }
                    imagePath.add(cur.getString(cur
                            .getColumnIndex(MediaStore.Images.Media.DATA)));
                    listImageByFolder.put(bucket, imagePath);
                } while (cur.moveToNext());
            }
    }