在Android 10或更高版本中,我使用MediaStore将文件保存在“下载”共享存储中。 我用来保存文件的代码如下:
GlobalScope.launch {
val values = ContentValues().apply {
put(MediaStore.Downloads.DISPLAY_NAME, "file.txt")
put(MediaStore.Downloads.MIME_TYPE, "text/plain")
put(MediaStore.Downloads.IS_PENDING, 1)
put(MediaStore.Downloads.RELATIVE_PATH,Environment.DIRECTORY_DOWNLOADS+ File.separator+"MyApp/SubDir")
}
val collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val item = contentResolver.insert(collection, values)!!
contentResolver.openFileDescriptor(item, "w", null).use {
FileOutputStream(it!!.fileDescriptor).use { outputStream ->
outputStream.write("test file".toByteArray())
outputStream.close()
}
}
values.clear()
values.put(MediaStore.Images.Media.IS_PENDING, 0)
contentResolver.update(item, values, null, null)
现在我的文件保存在Downloads / myApp / subDir / file.txt
如果是这样,如果我不知道该文件的Uri但知道用于保存该文件的RELATIVE_PATH,该如何读取该文件?
答案 0 :(得分:1)
现在可以借助SimpleStorage:
val fileList = MediaStoreCompat.fromRelativePath(this, Environment.DIRECTORY_DOWNLOADS)
val singleFile = MediaStoreCompat.fromRelativePath(this, Environment.DIRECTORY_DOWNLOADS + "/MyApp/SubDir/", "file.txt")