我想从作用域存储中删除一个图像文件,即从其他目录中显示的图像。我已经成功地显示了图像,但现在我无法在android 11中删除这些图像,删除图像的代码在android 10或更低版本上运行良好。
private void delSysMedia(ImageModel mi) {
ContentResolver cr = context.getContentResolver();
cr.delete(Images.Media.EXTERNAL_CONTENT_URI, Images.Media._ID + "=?", new String[]{String.valueOf(mi.getId())});
cr.delete(Images.Thumbnails.EXTERNAL_CONTENT_URI, Images.Thumbnails.IMAGE_ID + "=?", new String[]{String.valueOf(mi.getId())});
}以下是我在影像服务类中使用的代码
发布于 2021-11-26 06:54:38
要在Android11或更高版本上删除文件,你需要MediaStore.createDeleteRequest并传递一个你想要删除的Uri列表,它将向用户显示一个系统默认选择器,询问是否允许删除文件。
您可以使用以下代码删除图像文件。
val uris = arrayListOf<Uri?>()
val uriOfCurrentFile= getImgUri(fileObject.absolutePath)
if (uriOfCurrentFile!= null) {
uris.add(uriOfCurrentFile)
}
val intentSenderLauncher =
registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) {
if (it.resultCode == RESULT_OK) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Toast.makeText(context, "Deleted Successfully", Toast.LENGTH_SHORT).show()
}
}
}
//This function gets Uri of file for deletion
fun getImgUri(
path: String,
): Uri? {
try {
val checkFile = File(path)
Timber.e("checkDelete- $checkFile")
if (checkFile.exists()) {
var id: Long = 0
val cr: ContentResolver = activity?.contentResolver!!
val selection = MediaStore.Images.Media.DATA
val selectionArgs = arrayOf<String>(checkFile.absolutePath)
val projection = arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA)
val sortOrder = MediaStore.Images.Media.TITLE + " ASC"
val cursor = cr.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection,
"$selection=?", selectionArgs, null
)
if (cursor != null) {
while (cursor.moveToNext()) {
val idIndex = cursor.getColumnIndex(MediaStore.Images.Media._ID)
id = cursor.getString(idIndex).toLong()
Timber.e("checkFileID- $id")
try {
val photoUri: Uri = ContentUris.withAppendedId(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id
)
return photoUri
} catch (securityException: SecurityException) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val recoverableSecurityException =
securityException as? RecoverableSecurityException
?: throw securityException
recoverableSecurityException.userAction.actionIntent.intentSender
} else {
throw securityException
}
}
}
}
}
} catch (ex: Exception) {
ex.printStackTrace()
}
return null
}
//now you have list of Uri you want to delete
if (uris != null && uris.size > 0) {
var intentSender = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
MediaStore.createDeleteRequest(
activity!!.contentResolver,
uris
).intentSender
}
else -> null
}
intentSender?.let { sender ->
intentSenderLauncher.launch(
IntentSenderRequest.Builder(sender).build()
)
}
}请注意,如果不是图像文件,您将不得不用MediaStore.Video、MediaStore.Audio、MediaStore.Files等替换MediaStore.Images。
https://stackoverflow.com/questions/69989646
复制相似问题