Android_选择相册的照片

1. 一个小列子

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        btnChoosePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= 23) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);

                    } else {
                        //跳转到相册
                        openAlbum();

                    }
                } else {
                    //跳转到相册
                    openAlbum();
                }
            }
        });


    }

    private void initView() {
        btnChoosePhoto = findViewById(R.id.btn_choose_photo);
        ivImage = findViewById(R.id.iv_image);
    }

    /**
     * 打开相册
     */
    public void openAlbum() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, 1);
    }

    /**
     * 打开设置界面
     */
    public void openSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.fromParts("package", getApplication().getPackageName(), null));
        startActivity(intent);
    }

    @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 {
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        openSetting();
                    }
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {

                    if (Build.VERSION.SDK_INT >= 19) {
                        //Android 4.4 以上的。返回的照片的Uri不是真实的Uri, 是封装过的Uri。此时需要我们去解剖
                        handleImageOnKitKat(data);

                    } else if (Build.VERSION.SDK_INT < 19) {
                        //Android 4.4 以下的。
                       handleImageBeforeKitKat(data);
                    }
                }
                break;

        }
    }

    /**
     * 根据Uri来获取到图片对应的真实路径
     *
     * @param uri
     * @param selection
     * @return
     */
    public String getImagePath(Uri uri, String selection) {
        String path = null;
        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();
        }

        return path;
    }

    /**
     * 展示图片
     *
     * @param path
     */

    public void displayImage(String path) {
        if (path != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            ivImage.setImageBitmap(bitmap);
        } else {
            //路径为空 很难过
        }
    }

    @TargetApi(19)
    public void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();

        if (DocumentsContract.isDocumentUri(MainActivity.this, uri)) {
            //如果是document类型的Uri,那么通过document的id来处理
            String documentId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = documentId.split(":")[1];
                //等价于下面两句代码
                String [] array = documentId.split(":");
                String id = array[1];

                String selection = MediaStore.Images.Media._ID+"="+id;
                imagePath = getImagePath(uri,selection);
            }else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                imagePath = getImagePath(contentUri,null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            //如果是content类型的uri那么使用正常的uri
            imagePath = getImagePath(uri,null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            //如果uri是file 那么直接获取文件的路径
           imagePath = uri.getPath();
        }

        displayImage(imagePath);

    }

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

 

你可能感兴趣的:(Android基础知识)