About the problem of calling the mobile phone gallery to select a picture

  Some time ago, I studied the book "The First Line of Code", and then I followed the method of calling the mobile phone gallery. I found that it was unsuccessful. So after checking the information and the author Guo Lin's blog, I found that android was before API19 and The method after that is different and is hereby recorded. It is convenient for future study.

 

1. How to select cameras and pictures in activities

 

/**
     * A custom button click class that implements a click event listener to monitor button click events
     */
    class OnButtonListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                // selected image for click
                case R.id.btn_selpic:
                    doSelpic();
                    break;
                // click to take a photo
                case R.id.btn_takeaphoto:
                    doTakeaphoto();
                    break;
                default:
                    break;
            }
        }

        /**
         * The code to execute after clicking the select image button
         */
        private void doSelpic() {
            // Get the root directory of the device
            File sdDir = Environment.getExternalStorageDirectory();
            // create cache directory
            File cacheDir = new File(sdDir, "UPhotocache");
            // If the directory does not exist, create it
            if (!cacheDir.exists()) {
                cacheDir.mkdir();
            }
            // Create a File object to store the image after the license plate
            outputImage = new File(cacheDir, "output_image.jpg");
            try {
                // delete if exists
                if (outputImage.exists()) {
                    outputImage.delete();
                }
                // create a new file
                outputImage.createNewFile();
            } catch (IOException e) {
                e.printStackTrace ();
            }
            // start the activity that selects the image
            imageUri = Uri.fromFile (outputImage);
            Intent intent = new Intent("android.intent.action.GET_CONTENT");
            intent.setType("image/*");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, CHOOSE_FROM_ALBUM);
        }

        /**
         * The code executed after clicking the photo button
         */
        private void doTakeaphoto() {
            // Get the root directory of the device
            File sdDir = Environment.getExternalStorageDirectory();
            // create cache directory
            File cacheDir = new File(sdDir, "UPhotocache");
            // If the directory does not exist, create it
            if (!cacheDir.exists()) {
                cacheDir.mkdir();
            }
            // Create a File object to store the image after the license plate
            outputImage = new File(cacheDir, "output_image.jpg");
            try {
                // delete if exists
                if (outputImage.exists()) {
                    outputImage.delete();
                }
                // create a new file
                outputImage.createNewFile();
            } catch (IOException e) {
                e.printStackTrace ();
            }
            imageUri = Uri.fromFile (outputImage);
            // update the saved path
            imageSelPath = outputImage.getAbsolutePath();
            // start the camera program
            Intent takeIntent = new Intent("android.media.action.IMAGE_CAPTURE");
            takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            // Set the returned request code
            startActivityForResult(takeIntent, TAKE_PHOTO);
        }

    }

 

 

2. The method logic code called after returning the result

 

/**
     * Called when the selected activity returns data
     *
     * @param requestCode request code
     * @param resultCode result code
     * @param data data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Handle different return results according to the request code
        switch (requestCode) {
            case TAKE_PHOTO:
                // When the camera program returns the result is correct
                if (resultCode == RESULT_OK) {
                    // call clipper activity
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    intent.setDataAndType(imageUri, "image/*");
                    intent.putExtra("scale", true);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent, CROP_PHOTO);
                }
                break;
            case CHOOSE_FROM_ALBUM:
                // when the selected photo is returned correctly
                if (resultCode == RESULT_OK) {
                    / / Determine the version number of the mobile phone system
                    if (Build.VERSION.SDK_INT >= 19) {
                        handleImageOnKitKat(data);
                    } else {
                        handleImageBeforeKitkat(data);
                    }
                }
                break;
            case CROP_PHOTO:
                // When the result returned by the clipper is correct
                if (resultCode == RESULT_OK) {
                    // Pass the path of the cropped image to the activity that edits the image
                    Intent editIntent = new Intent(this, EditPicActivity.class);
                    editIntent.putExtra("EDIT_PIC", imageSelPath);
                    startActivity(editIntent);
                }
                break;
            default:
                break;
        }
    }

 

 

3. Judging the image selection code for different versions

/**
     * When the system is version 4.4 or above, the pictures must be read in the following ways
     *
     * @param data returned intent object
     */
    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Are you = data.getData ();
        imageUri = uri;
        if (DocumentsContract.isDocumentUri(this, uri)) {
            LogUtil.d("YYW", "Get the Uri information of the picture");
            // If the document type is uri, handle it by document id
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri
                    .getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
                LogUtil.d("YYW", "com.android.providers.media.documents");
            } 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);
                LogUtil.d("YYW", "com.android.providers.downloads.documents");
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // If it is not a Uri of document type, it is processed in the normal way
            imagePath = getImagePath(uri, null);
            LogUtil.d("YYW", "content");
        } else {
            LogUtil.d("YYW", "Unknown type");
        }
        imageSelPath = imagePath;
        displayImage(imageSelPath);
    }

    /**
     * When the system is below 4.4, the picture must be read in the following way
     *
     * @param data returned intent object
     */
    private void handleImageBeforeKitkat(Intent data) {
        Are you = data.getData ();
        imageUri = uri;
        imageSelPath = getImagePath(uri, null);
        displayImage(imageSelPath);
    }

    /**
     * Get the real path of the selected image
     *
     * @param uri image identifier
     * @param selection the option selected, can be empty
     * @return the real path of the selected image
     */
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //Get the real image path through Uri and 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();
        }
        return path;
    }

    /**
     * Method to pass image to edit activity
     *
     * @param imagePath image path
     */
    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(imageUri, "image/*");
            intent.putExtra("scale", true);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, CROP_PHOTO);
        } else {
            ToastUtil.show(this, R.string.fail_get_image);
        }
    }

 

Notice:

    Since the function I need to implement is: by taking a picture or selecting a picture and passing it to another activity (EditPicActivity), it may be different from the book. Readers should not copy directly. Code should be written on the basis of understanding.

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326705396&siteId=291194637