所有图像和视频均未显示在文件夹中
我希望所有图像和视频都显示文件夹,并且在应用程序中工作非常顺利
所有图像和视频中的应用程序都显示,但不与文件夹一起显示,所以我想要包含图像和视频的文件夹
添加权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
如果您的目标是 Android 11 或更高版本,请添加:
<application
android:requestLegacyExternalStorage="true"
现在检查应用程序中的权限:
if (ContextCompat.checkSelfPermission(
this, Manifest.permission.READ_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), REQUEST_CODE
)
}
创建一个名为
data
的 MediaFile
类:
data class MediaFile(val id: Long, val name: String, val mimeType: String, val path: String)
使用
ContentResolver
读取媒体文件:
fun getMediaFiles(contentResolver: ContentResolver): List<MediaFile> {
val mediaFiles = mutableListOf<MediaFile>()
val uri = MediaStore.Files.getContentUri("external")
val projection = arrayOf(
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.MIME_TYPE,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DATA
)
val selection = (MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE
+ " OR " + MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO)
val cursor = contentResolver.query(uri, projection, selection, null, null)
cursor?.use {
val idColumn = it.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID)
val nameColumn = it.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME)
val mimeTypeColumn = it.getColumnIndexOrThrow(MediaStore.Files.FileColumns.MIME_TYPE)
val pathColumn = it.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA)
while (it.moveToNext()) {
val id = it.getLong(idColumn)
val name = it.getString(nameColumn)
val mimeType = it.getString(mimeTypeColumn)
val path = it.getString(pathColumn)
mediaFiles.add(MediaFile(id, name, mimeType, path))
}
}
return mediaFiles
}
按文件夹对文件排序:
fun groupFilesByFolder(mediaFiles: List<MediaFile>): Map<String, List<MediaFile>> {
return mediaFiles.groupBy { file ->
File(file.path).parent ?: "Unknown"
}
}
注意:请添加注释和调试点,以便更好地理解事物的工作原理。