如何使用ACTION_OPEN_DOCUMENT_TREE Intent获取真实路径?

mcf*_*oft 11 android android-5.0-lollipop

我的应用程序下载并解压缩特定文件夹中的文件:

output = new FileOutputStream(realpath, true);
output.write(buffer, 0, bytesRead);

ZipFile zipFile = new ZipFile(realpath);
Run Code Online (Sandbox Code Playgroud)

随着新推出的ACTION_OPEN_DOCUMENT_TREEIntent,我想让用户选择该文件夹.

当测试我收到的值时onActivityResult,我会得到一个类似Path的路径/tree/primary:mynewfolder,这不是物理真实的路径/sdcard/mynewfolder.

Uri treeUri = data.getData();
String sPath = treeUri.getPath();
Log.v("Path from Tree ", sPath);
Run Code Online (Sandbox Code Playgroud)

我的解压方法需要真正的路径:

ZipFile zipFile = new ZipFile(realpath);
Run Code Online (Sandbox Code Playgroud)

如何/sdcard/mynewfolder从Lollipop(API 21和22)中提供的URI 获得真实路径?

Asi*_*eba 13

从URI获取真实路径的过程与之前相同,但稍加一些:

Uri uri = data.getData();
Uri docUri = DocumentsContract.buildDocumentUriUsingTree(uri, 
                        DocumentsContract.getTreeDocumentId(uri));
String path = getPath(this, docUri);
Run Code Online (Sandbox Code Playgroud)

可以在这里找到带有中间方法的getPath()方法的要点:getPath()

  • 它似乎不适用于 SD 卡路径。它是如何为你工作的?对我来说,它崩溃了,因为它返回 null(但它确定它是外部存储类型)。 (2认同)
  • @androiddeveloper您是否找到了外置SD卡的解决方案?我正面临类似的问题.无法获取外部SD卡中所选文件夹的真实路径. (2认同)
  • @CoolGuy哦。所以也许这可以帮助:https://www.programcreek.com/java-api-examples/index.php?source_dir=Augendiagnose-master/AugendiagnoseIdea/augendiagnoseLib/src/main/java/de/jeisfeld/augendiagnoselib/util/图像文件/FileUtil.java 。或者这个:/sf/answers/2531388401/。搜索“getFullPathFromTreeUri”。公开并尝试一下。如果有效,请将答案发布在这里。我不应该,因为我没有SD卡,所以我无法自己测试。 (2认同)