4

谷歌在 Android 10 上引入了 Scoped Storage,根据文档,我们可以使用 MediaStore API 在不请求权限的情况下写入公共目录。

在Android 10之前,当我们需要拍照并保存到Pictures时,代码如下:


private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            ...
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                                                  "com.example.android.fileprovider",
                                                  photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

String currentPhotoPath;

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
        imageFileName,  /* prefix */
        ".jpg",         /* suffix */
        storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    currentPhotoPath = image.getAbsolutePath();
    return image;
}

我们直接在 Pictures 中创建文件,并将文件 uri 放入 takePhotoIntent extra 中,当我们启动意图并拍照时,原始大小的照片将保存到 Pictures 目录中。

但是现在我们的目标是 android 10,根据文档,请求 WRITE_EXTERNAL_STORAGE 权限将照片保存到图片目录中是不必要的。

没有权限,我们不能创建文件然后获取文件的uri,将其放入intent extra。那么我们如何保存原始尺寸的照片呢?

4

0 回答 0