Call camera to take photos

Keywords: FileProvider Android

Call camera to take photos:

@Override
public void onClick(View v) {
    //Create a File object to store pictures after taking photos
    File outputImage = new File(getExternalCacheDir(),"output_image.jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    if (Build.VERSION.SDK_INT >= 24){
        //Convert File object to encapsulated Uri object
        imageUri = FileProvider.getUriForFile(MainActivity.this,"com.eventstest.fileprovider",outputImage);
    }else {
        //Convert File object to Uri object
        imageUri = Uri.fromFile(outputImage);
    }
    //Start camera program
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
     //Specify the action of Intent, and putExtra() specifies the output address of the picture. (implicit Intent)
    intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
    startActivityForResult(intent,TAKE_PHOTO);
    }

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case TAKE_PHOTO :
            if (resultCode == RESULT_OK) {
                try {
                    //Show pictures taken
                    //Parse the output_image.jpg image into a bitmap object. Then set up
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                    picture.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            break;
        default:
            break;
    }
}
  • Reading and writing SD card requires permission processing at run time. Instead, you can skip this step with the associated directory
  • If it is lower than Android 7.0, call Uri's fromFile() to convert the File object to a Uri object. Otherwise, call the getUriForFile() method of FileProvider to convert the File object into a encapsulated Uri object.
  • getUriForFile() takes three parameters 1.Context 2. It can be any unique string 3. The File object just created. Because it is considered unsafe for 7.0 to start using local real URIs directly. A FileExposedException exception will be thrown. FileProvider is a special content provider, which protects the data and can selectively share the encapsulated Uri to the outside, thus improving the security.

Posted by okuto1973 on Mon, 30 Mar 2020 22:04:32 -0700