android.os.FileUriExposedException错误

时间:2017-11-22 10:33:01

标签: android

首先,我已经检查了this similar question,但它似乎与我的代码不兼容。所以在这里,我的问题是我的应用程序崩溃,我试图打开相机,以拍摄照片并存储它。这是我正在使用的代码:

@RequiresApi(api = Build.VERSION_CODES.M)
private void dispatchTakePictureIntent() throws IOException {

    Log.i("Debug","dispatchTakePictureIntent entered");
    checkCameraPermissions();
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Makes sure there's an activity that handles the intent
    if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {

        File image = null;
        try{
            image = createImageFile();
        } catch (IOException ex) {
            Log.i("Debug", "IOException: " + ex);
        }
        // Continues if the file is created correctly
        if(image != null){

            Uri imageUri = Uri.fromFile(image); // <-- Here's the error 

            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO); 
            Log.i("Debug", "Photo succesfully saved " + takePictureIntent);
        }
    }
}

另外,我的方法createImageFile:

    private File createImageFile() throws IOException { 


    File imageRoot = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), appDirectoryName);

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File newFile = new File(imageRoot, imageFileName + ".jpg");
    if(!imageRoot.exists())
        if (!imageRoot.mkdirs())
            return null;

    mCurrentPhotoPath = newFile.getAbsolutePath();

    return newFile;

}

当我按下我在应用程序中的相机按钮时,我得到的错误:

FATAL EXCEPTION: main
              Process: com.odoo.quipons, PID: 13976
              android.os.FileUriExposedException: file:///data/user/0/com.odoo.myApp/files/Android/data/myApp/files/Pictures/JPEG_20171122_111843_.jpg exposed beyond app through ClipData.Item.getUri()

2 个答案:

答案 0 :(得分:0)

除了使用-FileProvider的解决方案外,还有另一种方法来解决此问题。简单的说 在Application.onCreate()中。这样,VM会忽略文件URI公开。只需将以下代码粘贴到Activity onCreate()中即可。

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); 
 StrictMode.setVmPolicy(builder.build());

答案 1 :(得分:0)

在android 10中,您具有商店图片的运行时存储权限。

选中此https://stackoverflow.com/a/33162451/11945183