1,权限
使用第三方权限框架XXPermissions
implementation 'com.github.getActivity:XXPermissions:12.2'
具体使用见作者使用文档,地址如下:GitHub - getActivity/XXPermissions: Android 权限请求框架,已适配 Android 11
2,遍历公共目录,查出一张图片,并记录下来
这里使用的是?Media?Store?API,通过遍历拿到第一张图片的uri,关键代码如下:
@RequiresApi(Build.VERSION_CODES.R)
fun queryImages(): List<MediaStoreImage> {
Log.d(TAG, "queryImages: ")
val images = mutableListOf<MediaStoreImage>()
val projection = arrayOf(
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.DATE_TAKEN
)
val sortOrder = "${MediaStore.Images.Media.DATE_TAKEN} DESC"
contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
null, // selection
null, // selectionArgs
sortOrder
)?.use { cursor ->
val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
val dateTakenColumn =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_TAKEN)
val displayNameColumn =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)
while (cursor.moveToNext()) {
val id = cursor.getLong(idColumn)
val dateTaken = Date(cursor.getLong(dateTakenColumn))
val displayName = cursor.getString(displayNameColumn)
val contentUri = Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id.toString()
)
Log.d(TAG, displayName)
val image = MediaStoreImage(id, displayName, dateTaken, contentUri)
if (imageUri == null) {
Log.d(TAG, "queryImages: imageUri == null")
imageUri = contentUri
requestDeletePermission(arrayListOf(contentUri))
}
images += image
// Log.d(TAG, image.toString())
}
}
Log.d(TAG, "Found ${images.size} images")
return images
}
3,删除图片
这里也是使用?Media?Store?API,传入一个 uri 的集合,我只在集合中放了一个元素,具体实现如下:
private fun requestDeletePermission(uriList: List<Uri>) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val pi = MediaStore.createDeleteRequest(getContentResolver(), uriList)
try {
startIntentSenderForResult(
pi.intentSender, 1, null, 0, 0,
0
)
} catch (e: SendIntentException) {
}
}
}
到此已能实现 android 11 上的文件删除操作
补充:
Media?Store 的更新问题,关于此问题的描述:我们向公共目录放入一张图片时,Media?Store 是不会立马更新,表现为用 MediaStore api 遍历时搜索不到这张图片
问题解决方式:
搜索前,用代码主动更新 MediaStore
关键代码如下:
fun scanFile() {
Log.d(TAG, "scanFile: ")
MediaScannerConnection.scanFile(
instance,
arrayOf(Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES).getPath()),
arrayOf("video/mp4", "audio/mp3", "image/jpeg"),
object : MediaScannerConnectionClient {
override fun onMediaScannerConnected() {
Log.d(TAG, "onMediaScannerConnected: ")
}
override fun onScanCompleted(path: String, uri: Uri) {
Log.d(TAG, "onScanCompleted: ")
Toast.makeText(instance,"更新完成",Toast.LENGTH_LONG).show()
}
})
}
demo 下载地址:
FileTest.zip-互联网文档类资源-CSDN下载
|