Why Environment.getExternalStoragePublicDirectory is not working in some devices(specially manufactured since early 2011)?

余生长醉 提交于 2020-07-05 07:35:31

问题


I am trying to store the images captured from camera to public storage directory, here is my part of code for storing image:

protected 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 */
                );
        return image;
    }

its working fine in most of the devices, but in some devices i get

java.io.IOException: open failed: ENOENT (No such file or directory)

So my question is why the same piece of code is working fine in most of the devices and why not in some devices and how to fix this issue?


回答1:


Use context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) instead.




回答2:


If you're storing your images in a public directory, I guess it is because you want to share those with other apps. You need to ask yourself the following question: "Do I want those files generated by my app to survive my app being uninstalled?" If the answer is no (which I recommend) you should use Context.getExternalMediaDirs() instead. Plus for API 19 and above, these directories do not need storage permissions!

If the answer is yes (O_o), you should use Environment.getExternalStorageDirectory() or Environment.getExternalStoragePublicDirectory(String). These always require storage permissions. Also, as you have already experienced and others pointed out, these directories might not yet exist. Check the API documentation for more info, but in short, you should call paths.mkdirs() before to ensure the dirs exist.




回答3:


you can use

File storageDir = new File(PATH_TO_PICTURES)

or

File storageDir =new File(PATH_TO_PICURES_EXTERNAL)

of course its better to check the directory first using this code:

if(storageDir.isDirectory())


来源:https://stackoverflow.com/questions/29004685/why-environment-getexternalstoragepublicdirectory-is-not-working-in-some-devices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!