欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android Uri 转Path

程序员文章站 2024-02-13 23:26:34
...

点击选择相册中的视频,获取所有本地视频文件。点击获取相册中的视频是正常的,但是获取文件管理中的视频时,会出现根据Uri找不到存储路径的问题。

在Android Uri 转 Path的过程中,发现在查询文件管理中的视频时,通过Uri查询系统媒体库得到的存储路径为null,但是可以通过拼接的方式来得到存储路径。

//Uri为:content://com.android.fileexplorer.myprovider/external_files/DCIM/Camera/VID_20201230_162057.mp4
private static String getMediaPathFromUri(Context context, Uri uri, String selection, String[] selectionArgs) {
        String path;
        String authroity = uri.getAuthority();
        path = uri.getPath(); //重点
        //方式一:拼接
        String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath(); // /storage/emulated/0
        if (!path.startsWith(sdPath)) {
        //path:::/external_files/DCIM/Camera/VID_20201230_162057.mp4
            int sepIndex = path.indexOf(File.separator, 1); //15
            if (sepIndex == -1) path = null;
            else {
                path = sdPath + path.substring(sepIndex);
            }
        }
        //方式二:从数据库查询
        if (path == null || !new File(path).exists()) {
            ContentResolver resolver = context.getContentResolver();
            String[] projection = new String[]{MediaStore.MediaColumns.DATA};
            Cursor cursor = resolver.query(uri, projection, selection, selectionArgs, null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    try {
                        int index = cursor.getColumnIndexOrThrow(projection[0]);
                        if (index != -1) path = cursor.getString(index);
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                        path = null;
                    } finally {
                        cursor.close();
                    }
                }
            }
        }
        return path;
    }

参考文章:
https://blog.csdn.net/chy555chy/article/details/104198956