我们可以使用 MediaStore API 删除图像文件吗?如果是的话怎么办

Teh*_*Mir 6 android file-permissions mediastore delete-file android-11

我需要在我的应用程序中使用后台服务一定时间后删除屏幕截图图像文件,并且使用上述方法工作正常

private void deleteTheFile(String path) {
    File fdelete = new File(path);
    if (fdelete.exists()) {
        if (fdelete.delete()) {
            getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(path))));
            Log.i(TAG, "deleteTheFile: file deleted");
        } else {
            Log.i(TAG, "deleteTheFile: file not dellleeettteeeddd");
        }
    }
Run Code Online (Sandbox Code Playgroud)

但正如每个人都知道 android R (11) 带来的变化所以我尝试更新我的应用程序

MANAGE_EXTERNAL_STORAGE 权限

但谷歌拒绝了我的更新说

问题:需要使用 Media Store API

您已请求访问所有文件访问权限,但您的应用程序的核心功能似乎只需要访问媒体文件。借助 MediaStore API,应用程序可以贡献和访问外部存储卷上可用的媒体,而无需访问所有文件权限。

请更新您的应用,以便该功能使用媒体存储 API 并删除所有文件访问 (MANAGE_EXTERNAL_STORAGE) 权限。

但我以前从未使用过媒体存储API,我不知道它是否可以用它删除图像文件,因为删除文件属于可写部分

小智 3

使用createDeleteRequest

private fun deleteImages(uris: List<Uri>) {
  val pendingIntent = MediaStore.createDeleteRequest(contentResolver, uris.filter {
    checkUriPermission(it, Binder.getCallingPid(), Binder.getCallingUid(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != PackageManager.PERMISSION_GRANTED
  })
  startIntentSenderForResult(pendingIntent.intentSender, REQ_CODE, null, 0, 0, 0)
}
Run Code Online (Sandbox Code Playgroud)

使用内容解析器

// Remove a specific media item.
val resolver = applicationContext.contentResolver

// URI of the image to remove.
val imageUri = "..."

// WHERE clause.
val selection = "..."
val selectionArgs = "..."

// Perform the actual removal.
val numImagesRemoved = resolver.delete(
        imageUri,
        selection,
        selectionArgs)
Run Code Online (Sandbox Code Playgroud)

https://github.com/android/storage-samples/tree/main/MediaStore

这是一个android官方示例,您可以按照它来了解并尝试使用MediaStoreAPI来实现它