Capture image without permission with Android 6.0

前端 未结 5 1128
庸人自扰
庸人自扰 2021-02-04 07:29

I need to let the user take a picture (from the gallery or from a camera app) with Android 6.0.

Because I don\'t need to control the camera, I wanted to use an intent as

5条回答
  •  既然无缘
    2021-02-04 08:10

    Since the camera app cannot access to the private dirs of your app, It's your applications duty to write the photo file to that directory. I'm not really sure about this but this works for me:

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
                .format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
    }
    
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
            takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
        } catch (IOException ex) {
            // Error occurred while creating the File
            Log.e(TAG, "Unable to create Image File", ex);
        }
    
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
        } else {
            takePictureIntent = null;
        }
    }
    

    But you still need WRITE_EXTERNAL_STORAGE permission before KITKAT:

    
    

提交回复
热议问题