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

标签 android

我想通过打开由 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);

screenshot

最佳答案

外部存储 URI 的形式如下:

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

其中 root 是存储介质的根目录,%3A 只是一个转义冒号,path 是相对于根(也转义)。

在具有模拟主存储的设备(即现代 Android 设备)上,主存储的根目录(即 /sdcard)通常称为 primary。在其他情况下,它似乎是媒体 ID(用连字符分隔的 4+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;
}

关于android - 如何通过权限为 "com.android.externalstorage.documents"的uri获取文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44226029/

相关文章:

android - android中的自定义进度条,如gif

android - 将视频文件放在android项目中的什么位置

android - 在 Android 设备上拍摄视频并在 iOS 设备上播放

android - 在 Android 上以编程方式检测和更改数据连接 (GPRS/UMTS)

android - 即使缩小图像,Flutter App 大小仍然相同

android - 锁定水平 View

java - TextView 在水平布局中不可见

android - 不同帐户在 Google Play 商店发布的两个 apk 文件是否可以使用相同的 key / keystore 进行签名?

android - 检查后复选框错误不会消失

java - 如何在 WebView 中捕获链接页面加载?