【问题标题】:Can we delete an image file using MediaStore API? if yes then how我们可以使用 MediaStore API 删除图像文件吗?如果是,那么如何
【发布时间】:2021-08-20 04:54:39
【问题描述】:

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

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");
        }
    }

但众所周知,android R (11) 带来的变化 所以我尝试用

更新我的应用程序

MANAGE_EXTERNAL_STORAGE 权限

但谷歌拒绝了我的更新说

问题:需要使用 Media Store API

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

请更新您的应用,以便该功能使用 Media Store API 和 删除所有文件访问 (MANAGE_EXTERNAL_STORAGE) 权限。

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

【问题讨论】:

    标签: android file-permissions delete-file mediastore android-11


    【解决方案1】:

    使用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)
    }
    

    使用内容解析器

    // 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)
    

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

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

    【讨论】:

    • 谢谢你,我会尝试他们并更新结果,我是否还必须为他们使用任何权限?
    • &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt;&lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" /&gt;
    • 抱歉,maxSdkVersion 28 是什么意思,它不会在 sdk 29 和 30 上工作吗?
    • 不删除需要写入权限的文件,直到 API 28 才使用 maxSdkVersion,否则 API 低于 29,您将收到权限问题错误
    • 所以你的意思是如果我设置 max sdk 28,我的应用程序仍然可以删除 sdk 29 和 30 中的文件
    猜你喜欢
    • 1970-01-01
    • 2013-12-29
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    相关资源
    最近更新 更多