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, 感謝此文章,解決了我的問題.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM