在使用ACTION_OPEN_DOCUMENT_TREE打开时,需要调用许可请求并获得授权后,才能使用该目录下的所有文件和文件夹。在选择目录时,需要保证选择的目录是存储卡的顶级目录,而不是子目录。在获取树权限后,需要使用Uri获取该目录的访问权限,并在代码中进行访问控制。
以下是示例代码:
fun requestStoragePermission(activity: Activity, requestCode: Int) {
val storagePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE
if (ContextCompat.checkSelfPermission(activity, storagePermission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, arrayOf(storagePermission), requestCode)
}
}
val REQUEST_CODE_OPEN_DOCUMENT_TREE = 1
val EXPORT_FOLDER_NAME = "Exported Files"
fun createFile() {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
flags = Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
}
startActivityForResult(intent, REQUEST_CODE_OPEN_DOCUMENT_TREE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CODE_OPEN_DOCUMENT_TREE && resultCode == RESULT_OK) {
data?.data?.also { uri ->
val folderName = EXPORT_FOLDER_NAME
val directory = DocumentsContract.getTreeDocumentId(uri)
val documentUri = DocumentsContract.buildDocumentUriUsingTree(uri, directory)
val folderUri = DocumentsContract.createDocument(contentResolver, documentUri, DocumentsContract.Document.MIME_TYPE_DIR, folderName)
val fileUri = DocumentsContract.createDocument(contentResolver, folderUri, "text/plain", "example.txt")
contentResolver.openFileDescriptor(fileUri, "w")?.use {
FileOutputStream(it.fileDescriptor).use { output ->
val text = "Hello world!"
output.write(text.toByteArray())
output.flush()
}
}
revokeUriPermission(fileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
}
}