如何通过权限为"com.android.externalstorage.documents"的URI获取文件路径

4

我希望通过使用startActivityForResult来打开一个文件选择器并获取文件路径,使用的Intent是Intent.ACTION_GET_CONTENT和setType(*/*),但是当我从"Nexus 5X"选项中选择打开时,返回的URI是"com.android.externalstorage.documents",请问如何处理这种类型的URI。

以下是相关代码:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.ACTION_DEVICE_STORAGE_OK, true);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("*/*");
startActivityForResult(intent, FILE_ADD_ACTION_REQUEST_CODE);

截图


那不是完整的“返回URI”。 - greenapps
其中一个完整的URI是“content://com.android.externalstorage.documents/document/home%3Ademo_decry.mp4”。 - sohnyi
2个回答

5

外部存储URI的格式如下:

content://com.android.externalstorage.documents/root%3Apath

在存储介质中,root是根目录,%3A仅是冒号的转义字符,path是相对于根目录的文件系统路径(同样需要进行转义)。

对于带有模拟主存储(即现代Android设备)的设备,主存储器(即/sdcard)的根目录通常称为primary。在其他情况下,它似乎是媒体ID(由连字符分隔的4个十六进制数字)。

您还可以尝试使用此方法(需要API 21以获得完整功能):

 public static String getRealPathFromURI_API19(Context context, Uri uri) {
    String filePath = "";

    // ExternalStorageProvider
    String docId = DocumentsContract.getDocumentId(uri);
    String[] split = docId.split(':');
    String type = split[0];

    if ("primary".equalsIgnoreCase(type)) {
        return Environment.getExternalStorageDirectory() + "/" + split[1];
    } else {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            //getExternalMediaDirs() added in API 21
            File[] external = context.getExternalMediaDirs();
            if (external.length > 1) {
                filePath = external[1].getAbsolutePath();
                filePath = filePath.substring(0, filePath.indexOf("Android")) + split[1];
            }
        } else {
            filePath = "/storage/" + type + "/" + split[1];
        }
        return filePath;
}

仅提供代码答案并不鼓励,因为它们对于未来的读者提供的信息不多,请在您编写的代码上提供一些解释。 - WhatsThePoint
我已经编辑了答案,添加了一个介绍并删除了与问题无关的代码部分。 - user149408

0
如何处理这种类型的URI?
使用ContentResolveropenInputStream()来获取由Uri标识的内容上的InputStream

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接