Android 调用相册返回路径以及返回Uri的总结

今天在做调取相册返回的时候, 出现一种新型的类型, 也许是我以前没碰到过这种类型吧.如下

content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Ftest.jpg

这个转换用以前使用的方法转换不成功,emmm, 很久没使用过Android了吧,有点头蒙了.下面是以前的使用方法

//获取权限
    private void getPermission() {
        //如果没有权限,Android6.0之后,必须动态申请权限(记住这个套路)
        if (ContextCompat.checkSelfPermission(MainActivity2.this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //如果用户已经拒绝过一次权限申请,该方法返回true
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    MainActivity2.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                //提示用户这一权限的重要性
                Toast.makeText(MainActivity2.this, "读取SD卡功能是本应用的核心"
                                + "功能,如果不授予权限,程序是无法正常工作!",
                        Toast.LENGTH_SHORT).show();
            }
            //请求权限
            ActivityCompat.requestPermissions(MainActivity2.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        } else { //权限已被授予,打开相册
            openAlbum();
        }
    }

    @Override
    //弹出一个权限申请的对话框,并且用户做出选择后,该方法自动回调
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] ==
                        PackageManager.PERMISSION_GRANTED) {
                    //权限已授予,打开相册
                    openAlbum();
                } else {
                    //权限未授予
                    Toast.makeText(this, "未授予权限的情况下,程序无法正常工作",
                            Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            // 判断手机版本
            if (Build.VERSION.SDK_INT >= 19) {
                // 4.4及以上系统使用这个方法处理图片
                handleImageOnKitKat(data);
            } else {
                // 4.4以下系统使用这个方法处理图片
                handleImageBeforeKitKat(data);
            }
        }

    }


    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        Log.d("TAG", "handleImageOnKitKat: uri is " + uri);
        Log.d("TAG", "handleImageOnKitKat : " + uri.getAuthority());
        Log.d("TAG", "handleImageOnKitKat urlPath: " + uri.getScheme());
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri,则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            Log.d("TAG", "handleImageOnKitKat: docId" + docId);

            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri,则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri,直接获取图片路径即可
            imagePath = uri.getPath();
        }
        displayImage(imagePath); // 根据图片路径显示图片
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        Log.e("TAG", "getImagePath: " + path);
        return path;
    }

    private void displayImage(String imagePath) {
        this.imagePath = imagePath;
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            ivAvatarEdit.setImageBitmap(bitmap);
        } else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }

之前的路径为:

content://com.android.providers.media.documents/document/image%3A128991

 然后现在的路径为:

content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Ftest.jpg

这个我测试了下, 会报java.lang.NumberFormatException异常, 通过查找, 就是这行代码错误, 如下

Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(docId));
docId不能转换为长整型

通过查看log日志:docId, 发现, 其实他已经是一个文件路径了, 如:draw:/storage/emulated/0/Download/test.jpg, 可以直接通过截取给替换掉就可以当成路径使用了, 替代代码如下

            在我上方的handleImageOnKitKat函数里else if中修改
        else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                // 下载目录
                if (docId.startsWith("raw:")) {
                    imagePath = docId.replaceFirst("raw:", "");
                } else {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(docId));
                    imagePath = getImagePath(contentUri, null);
                }
            }

 这样问题就解决了, 如果有不会的可以留言,一起探讨交流.

本博客借鉴了:https://blog.csdn.net/androidzmm/article/details/82886392, 感谢此文章,解决了我的问题.

原文地址:https://www.cnblogs.com/MrChen-/p/14607523.html