最近写了个自定义相册模块,其中比较核心的算是查询照片了,直接上代码吧
val contentUri = MediaStore.Files.getContentUri("external")
val sortOrder = MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC"
val selection =
"(${MediaStore.Files.FileColumns.MEDIA_TYPE} = ? OR ${MediaStore.Files.FileColumns.MEDIA_TYPE} = ?) AND ${MediaStore.MediaColumns.SIZE} > 0"
val selectionAllArgs = arrayOf(MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE.toString())
val projections = arrayOf(
MediaStore.Files.FileColumns._ID,
MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME,
MediaStore.MediaColumns.DATE_MODIFIED, MediaStore.MediaColumns.MIME_TYPE,
MediaStore.MediaColumns.WIDTH, MediaStore.MediaColumns.HEIGHT,
MediaStore.MediaColumns.SIZE, MediaStore.Video.Media.DURATION
)
val cursor = context.contentResolver.query(contentUri, projections, selection, selectionAllArgs, sortOrder) ?: return
if (cursor.moveToFirst()) {
val idCol = cursor.getColumnIndex(MediaStore.MediaColumns._ID)
val pathCol = cursor.getColumnIndex(MediaStore.MediaColumns.DATA)
val nameCol = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
val mimeType = cursor.getColumnIndex(MediaStore.MediaColumns.MIME_TYPE)
do {
val id = cursor.getString(idCol)
//这里得到path其实就可以利用glide来显示照片了,但还是建议用uri
val path = cursor.getString(pathCol)
val name = cursor.getString(nameCol)
val type = cursor.getString(mimeType)
//过滤gif
if (name.endsWith(".gif", true)) {
continue
}
//过滤视频
if (type.contains("video")) {
continue
}
val file = File(path)
if (!file.exists() || !file.isFile) {
continue
}
//这里拿到uri
val uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
//这里可以对照片进行分类操作,
...
} while (cursor.moveToNext())
}
cursor.close()
数据库查询要放到工作线程处理,而且别忘了申请外部存储读写权限