一般我们手机里的图片很多,一次查询出来的话可能没必要,因此分页查询很方便的解决了问题。 Android 8.0及以上使用 queryArgs 分页(以用来兼容Android11,android 11 不可用 sortOrder 分页,否则会报错,因为谷歌从Android11开始没有了)
,Android 8.0 以下使用 sortOrder 分页
直接上代码,在自己的ViewModel中使用:
val files = mutableListOf<AlbumBean>()
val fileLiveData: MutableLiveData<MutableList<AlbumBean>> = MutableLiveData()
val mPageSize = 100
val projection = arrayOf(
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA,
MediaStore.Files.FileColumns.MIME_TYPE,
MediaStore.Files.FileColumns.SIZE,
MediaStore.Files.FileColumns.TITLE
)
/**
* 分页查询媒体库
* Android 8.0及以上使用 queryArgs 分页(以用来兼容Android11,android 11 不可用 sortOrder 分页)
* Android 8.0以下使用 sortOrder 分页
* page从0开始
*/
fun queryMediaStoreImages(page: Int) {
viewModelScope.launch(Dispatchers.IO) {
if (page == 0) {
files.clear()
}
var list = mutableListOf<AlbumBean>()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
val uri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val queryArgs = Bundle()
// 设置倒序
queryArgs.putInt(
ContentResolver.QUERY_ARG_SORT_DIRECTION,
ContentResolver.QUERY_SORT_DIRECTION_DESCENDING
)
// 设置倒序条件--文件添加时间
queryArgs.putStringArray(
ContentResolver.QUERY_ARG_SORT_COLUMNS,
arrayOf(MediaStore.Files.FileColumns.DATE_ADDED)
)
// 分页设置
queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, page * mPageSize)
queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, mPageSize)
val cursor = MyApp.instance.getContentResolver().query(
uri,
projection,
queryArgs,
null
)
if (cursor != null) {
while (cursor.moveToNext()) {
val id =
cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID))
val path =
cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA))
val title =
cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.TITLE));
val bean = AlbumBean()
bean.name = title
bean.path = path
bean.id = id.toLong()
list.add(bean)
}
cursor.close()
}
} catch (e: Exception) {
}
} else {
try {
val uri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
var selection: String? = null
var selectionArgs: Array<String>? = null
// 倒序+分页
val sortOrder =
MediaStore.Images.Media.DATE_ADDED + " DESC limit " + mPageSize + " offset " + page * mPageSize
val cursor = MyApp.instance.getContentResolver().query(
uri,
projection,
selection,
selectionArgs,
sortOrder
)
if (cursor != null) {
while (cursor.moveToNext()) {
val id =
cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID))
val path =
cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA))
val title =
cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.TITLE))
// 接下来使用list保存即可
val bean = AlbumBean()
bean.name = title
bean.path = path
bean.id = id.toLong()
list.add(bean)
}
cursor.close()
}
} catch (e: Exception) {
}
}
files.addAll(list)
fileLiveData.postValue(list)
}
}
|