一、前言

在Android12版本上面使用MediaStore时候有时候会遇到以下错误:

java.lang.IllegalArgumentException: Invalid token /storage/emulated/0/Download/s-kz-02.jpg

其代码编写如下:

   val res: Int = contentResolver.delete(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        MediaStore.Images.Media.DATA + "= \"" + filePath + "\"",
                        null
                    )

该问题的解决方式为,在高版本授予全部文件访问权限。其代码使用方式如下:
https://blog.csdn.net/Mr_Tony/article/details/122102953

**注:**如果使用MediaStore.Images.Media._ID的方式删除也是删不掉的。另外File文件删除也删不掉(因为没权限)

二、原因

AndroidQ (version 29以上)对文件访问进行了限制,如果想对文件进行修改的话需要用户授权。所以如果想绕开用户授权的话只能使用上述方式。下面给出常规方式,代码如下:

private const val DELETE_PERMISSION_REQUEST = 0x1033
private val permissionNeededForDelete: IntentSender =
recoverableSecurityException.userAction.actionIntent.intentSend
 startIntentSenderForResult(
                    permissionNeededForDelete,
                    DELETE_PERMISSION_REQUEST,
                    null,
                    0,
                    0,
                    0,
                    null
                )
//上述现获取授权,下一步再调用MediaStore进行删除:
 getApplication<Application>().contentResolver.delete(
                    image.contentUri,
                    "${MediaStore.Images.Media._ID} = ?",
                    arrayOf(image.id.toString())
                )

**注:**倘若已经通过SAF获取授权后则可以通过Uri的方式进行批量删除。
参考代码如下:

  1. https://github.com/android/storage-samples/tree/main/MediaStore
  2. https://stackoverflow.com/questions/60516401/android-q-recoverablesecurityexception-not-granting-access
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐