weixin_46349681 2021-04-17 00:54 采纳率: 0%
浏览 77

android 如何通过来自DownloadsProvider的uri获取图片真实路径?

写了一个需要获取图片真实路径的app,在API29运行,就是打开相册返回选中图片的uri,再通过uri获取真实路径,在网上查看了几篇文章,在从DownloadsProvider中获取真实路径的代码是下面这段:

String documentId = DocumentsContract.getDocumentId(uri);
if (isDownloadsDocument(uri)) {
    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
filePath = getDataColumn(context, contentUri, null, null);
}


然而问题是从DownloadsProvider中获取的uri的documentId都是“msf:+一个数字”的形式,例如“msf:25”,所以在Long.valueOf(documentId));这个地方就会报错,因为documentId不是纯数字而是包含英文的形式,但是我直接吧msf:这个非数字的部分去掉也不能获取到真实路径,所以应该是有另外某种转化方法可以获取到真实路径的。

但是为什么在网上查到的方法都是像上面代码这样会报错的方法,如果想从DownloadsProvider中获取真实路径应该怎么做呢?

  • 写回答

1条回答 默认 最新

  • 码农阿豪@新空间 新星创作者: 前端开发技术领域 2024-07-16 09:43
    关注
    让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言
    从DownloadsProvider中获取真实路径可以使用以下方法:
    private String getRealPathFromURI(Context context, Uri uri) {
        String filePath = null;
        if (DocumentsContract.isDocumentUri(context, uri)) {
            String documentId = DocumentsContract.getDocumentId(uri);
            if (uri.getAuthority().equals("com.android.providers.downloads.documents")) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(documentId));
                filePath = getDataColumn(context, contentUri, null, null);
            } else if (uri.getAuthority().equals("com.android.providers.media.documents")) {
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = { id };
                Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                filePath = getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            filePath = getDataColumn(context, uri, null, null);
        }
        return filePath;
    }
    private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = null;
        String filePath = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                filePath = cursor.getString(index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return filePath;
    }
    

    这段代码可以处理从DownloadsProvider中获取到的uri,包括处理不同类型的文档提供者(downloads和media),并正确地获取到真实路径。您可以在您的应用中使用这段代码来获取真实路径。

    评论

报告相同问题?