使用 Uri 删除文件

Gik*_*s91 4 android

我尝试以这种方式删除文件:

getContentResolver().delete(uri, null, null)
Run Code Online (Sandbox Code Playgroud)

当 uri 为 content://media/external/video/media/1214 时,它适用于视频,但不适用于音频文件 content://media/external/audio/media/1212。

我需要它来删除从相机和录音机收到的文件,因为目前这些文件位于我的应用程序目录和 SD 卡上。

有人可以帮助我吗?怎么了?

Kas*_*mir 7

科特林扩展:

fun File.delete(context: Context): Boolean {
   var selectionArgs = arrayOf(this.absolutePath)
   val contentResolver = context.getContentResolver()
   var where: String? = null
   var filesUri: Uri? = null
   if (android.os.Build.VERSION.SDK_INT >= 29) {
      filesUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
      where = MediaStore.Images.Media._ID + "=?"
      selectionArgs = arrayOf(this.name)
   } else {
      where = MediaStore.MediaColumns.DATA + "=?"
      filesUri = MediaStore.Files.getContentUri("external")
   }

   val int = contentResolver.delete(filesUri!!, where, selectionArgs)

   return !this.exists()
}
Run Code Online (Sandbox Code Playgroud)

像这样调用:

val file = File(uri.path)
file.delete(applicationContext)
Run Code Online (Sandbox Code Playgroud)