由DocumentsUI 得到文件path

来源:互联网 发布:软件界面素材下载 编辑:程序博客网 时间:2024/05/21 07:11

uriForCapture = content://com.android.providers.media.documents/document/video%3A98

uriForCapture = content://media/external/video/media/98

针对这2中uri第二种通过查多媒体数据库很容易得到文件path,类似:uriString = /storage/emulated/0/DCIM/Camera/***.mp4

但是第一种不能直接查询到。

 

可以尝试以下方法:

  
    private String getPathFromDocmentsUri(Context ctx,Uri docUri) {
       String imagePath = null;

       if (DocumentsContract.isDocumentUri(ctx, docUri)) {
            String docId = DocumentsContract.getDocumentId(docUri);
            if ("com.android.externalstorage.documents".equals(docUri.getAuthority())) {
                String dir = docId.split(":")[0];
                String selec= docId.split(":")[1];
                imagePath = "/storage/"+dir+"/"+selec;
                return imagePath;
            }else if ("com.android.providers.media.documents".equals(docUri.getAuthority())) {
                String id = docId.split(":")[1];
                //String selection = MediaStore.Video.Media._ID + "=" + id;
                imagePath = getPathFromDoc(MediaStore.Video.Media.EXTERNAL_CONTENT_URI.toString()+"/"+id);
            } else if ("com.android.providers.downloads.documents".equals(docUri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(docId));
                imagePath = getPathFromDoc(contentUri.toString());
            }
        }
       return imagePath;
    }

 

    private String getPathFromDoc(String docUri) {
        String imagePath = null;
        Log.d(TAG, "getPathFromDoc ,imageUrl= " + docUri);
        Uri uri = Uri.parse(docUri);
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor imageCursor = mContext.getContentResolver().query(uri, proj, null, null, null);

        if (imageCursor != null) {
            if (imageCursor.moveToFirst()) {
                int image_column_index = imageCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                imagePath = imageCursor.getString(image_column_index);
            }
            imageCursor.close();
        }
        return imagePath;
    }

 

 

0 0