AndroidSAF-ACTION_OPEN_DOCUMENT_TREE无法从子目录创建和列出文件。
创始人
2024-10-10 00:31:53
0

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

相关内容

热门资讯

截至目前!wepoker底牌透... 截至目前!wepoker底牌透视脚本,红龙poker辅助,操作教程(存在有挂)-哔哩哔哩1、不需要A...
据通报!wepoker黑侠辅助... 据通报!wepoker黑侠辅助器正版下载(透视)一直是有挂的(今日头条开挂辅助插件)-哔哩哔哩wep...
这一现象值得深思!wepoke... 这一现象值得深思!wepoker私人定制透视(透视)一贯确实有挂(有挂详细开挂辅助下载)-哔哩哔哩1...
据玩家消息!pokemmo脚本... 据玩家消息!pokemmo脚本辅助,hhpoker真的假的,步骤教程(有挂分析)-哔哩哔哩1、pok...
围绕透视问题!wepoker怎... 围绕透视问题!wepoker怎么设置房间,wepoker安装教程,要领教程(有挂技术)-哔哩哔哩1)...
有玩家发现!wepoker私人... 有玩家发现!wepoker私人局辅助器怎么用(透视)果然真的是有挂(真是有挂开挂辅助下载)-哔哩哔哩...
经核实!hhpoker有透视功... 经核实!hhpoker有透视功能吗(透视)其实真的有挂(有挂秘诀开挂辅助软件)-哔哩哔哩1、完成hh...
长期以来!poker红龙辅助,... 长期以来!poker红龙辅助,pokemmo脚本辅助,烘培教程(有挂方略)-哔哩哔哩1、上手简单,内...
近日!pokemmo辅助器手机... 近日!pokemmo辅助器手机版下载(透视)其实是有挂的(的确有挂开挂辅助软件)-哔哩哔哩1、pok...
围绕透视问题!wepoker私... 围绕透视问题!wepoker私局代打,hhpoker真的假的,方式教程(存在有挂)-哔哩哔哩1、围绕...