java - 在不使用 findFiles() 的情况下获取作为文档树子项的 DocumentFile

标签 java android storage-access-framework documentfile

我有一个从 ACTION_OPEN_DOCUMENT_TREE 获得的树 URI , 如何在不使用 findFiles() 的情况下获得作为这棵树的子树的 DocumentFile ?假设我知道如何获取它的 documentId、它的绝对路径或它的 URI。我需要与文档树关联的权限。

这是我现在拥有的:

DocumentFile rootTree = DocumentFile.fromTreeUri(context, rootTreeUri);
DocumentFile docFile = rootTree.findFile(fileName);

它返回 docFile作为 TreeDocumentFile,我根的 child 。我有写权限,可以使用 createFile()在它上面,因为它在 ACTION_OPEN_DOCUMENT_TREE 的文档树下.

所以它有效但是findFile()真的很慢。

如果我尝试像这样使用 DocumentsContract:

// I know how to build the documentId from the file's absolute path
Uri uri = DocumentsContract.buildTreeDocumentUri(rootTreeUri.getAuthority(), documentId);
DocumentFile docFile = DocumentFile.fromTreeUri(context, uri);
// Result: "content://com.android.externalstorage.documents/tree/1A0E-0E2E:myChildDirectory/document/1A0E-0E2E:myChildDirectory"

它返回一个以 docFile 为根的新 TreeDocumentFile , 不是 docFile作为我的原始文档树(根)的 child 。所以我没有这棵树的写权限。

如果我这样尝试:

Uri docUri = DocumentsContract.buildDocumentUriUsingTree(rootTreeUri, documentId);
// Result: "content://com.android.externalstorage.documents/tree/1A0E-0E2E:/document/1A0E-0E2E:myChildDirectory"

我得到一个实际上看起来像我想要的 URI,但它是一个 URI,而不是一个 DocumentFile。

如果我执行与上面相同的操作,但使用 fromTreeUri() 从这个 uri 构建一个 DocumentFile:

Uri docUri = DocumentsContract.buildDocumentUriUsingTree(rootTreeUri, documentId);
DocumentFile docFile = DocumentFile.fromTreeUri(context, docUri);
// Result: "content://com.android.externalstorage.documents/tree/1A0E-0E2E:/document/1A0E-0E2E:"

我得到的是原始树 DocumentFile,而不是代表 child 的 DocumentFile。

最佳答案

当前的 API 无法满足您的需求。获得 TreeDocumentFile 的唯一方法(DocumentFile 的私有(private)子类,支持createFilecreateDirectorylistFilesrenameTo) 是通过 DocumentFile.fromTreeUri(它只为您提供您找到的根树 URI)或通过现有 TreeDocumentFilelistFiles() 方法,这是 findFile 内部使用的方法。

您应该在 issuetracker.google.com 上提交功能请求添加一个新的静态方法来满足您的需要。

关于java - 在不使用 findFiles() 的情况下获取作为文档树子项的 DocumentFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46180851/

相关文章:

android - zxing 库最小 SDK 和 core.jar

java - MediaHTTPConnectionEx com.lge.media.MediaHTTPConnectionEx 442 寻求异常 toString : java. io.IOException

java - java中从数组中检索元素的成本

Java 不是确定性的?

android - 未找到 TargetPlatform.android_x86 的应用程序

android - 如何向存储访问框架表明我不再需要加载动画?

java - Android 无法对 SD 卡进行写入和删除操作

java - Android 设备监视器将无法从 Android Studio 或终端启动 - UnsupportedClassVersionError

java - 在 java 中我们可以使用 list.remove(int index) 来删除该索引中的项目,如果列表很大而我们只能使用 long 来存储索引怎么办?

android - 在 Android N 上浏览可移动 USB OTG,存储访问框架真的是唯一的方法吗?