Android development template code (1) -- simply open the gallery and select photos

Keywords: Android less

First, post the sample code

//Check permissions
    public void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            //Found no permission, call requestPermissions Method to request permission from the user, requestPermissions Receive three parameters, the first one is context,The second is a String Array, we will apply for the permission
            //The third is the request code, as long as it is the only value
        } else {
            openAlbum();//Open album with permission
        }
    }

    public void openAlbum() {
        //adopt intent Open album, using startactivityForResult Method start actvity,Will return to onActivityResult Method, so we have to copy onActivityResult Method
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }
    //Pop up window to request permission from user


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);//The authorization window will pop up. This statement can also be deleted without any impact
        //The authorization result of the user is obtained and saved in grantResults Medium, judgment grantResult To determine the next operation
        switch (requestCode) {
            case 1:

                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(this, "Authorization failed, unable to operate", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        handleImageOnkitKat(data);//Above 4.4 Version use this method to process pictures
                    } else {
                        handleImageBeforeKitKat(data);//Less than 4.4 Version use this method to process pictures
                    }
                }
                break;
            default:
                break;
        }
    }

    @TargetApi(19)
    private void handleImageOnkitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            //If it is document Of type uri,Then pass document id Handle
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];//Parse out the 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.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }

        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
        }
        displayImage(imagePath);
    }

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

    //Get picture path
    public String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);   //Content provider
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));   //Get path
            }
        }
        cursor.close();
        return path;
    }

    //Show pictures
    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitImage = BitmapFactory.decodeFile(imagePath);//Format picture

            mImage.setImageBitmap(bitImage);//by imageView Set up picture

        } else {
            Toast.makeText(MainActivity.this, "Failed to get picture", Toast.LENGTH_SHORT).show();
        }
    }

instructions:

1, Add memory card permissions to the Android manifest file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2, Find the Button or imageButton through findviewbyid, and bind the listening event

3, Copy the above sample code and put it under the onClick event. At the same time, add a global static variable

 

4, Call the checkPermission method in the click event of button or imageButton

5, Find the ImageView through findviewbyid, modify the object name of the call set picture in the display method to the object name of the ImageView in the actual project. For details, see the code in red. Modify the image

Simple logic introduction:

After drawing a flow chart, the logic is still clear, so I won't explain it too much here

 

PS: in fact, you can also add the operation of cutting pictures at the last side. After setting up the pictures, I searched the information and saw it very stupidly. I will supplement it after thorough research

Demo download

Posted by perfume on Sun, 26 Apr 2020 08:15:21 -0700