FileNotFoundException:open failed:EACCES(权限被拒绝)

时间:2016-09-26 00:13:58

标签: java android

在模拟器中(我使用genymotion)它工作正常,但是当我在真实设备上运行它(我的手机是华硕ZenFone Laser 5.0)时会抛出一个文件错误

java.io.FileNotFoundException:/storage/emulated/0/cam20160926_075819.jpg:open failed:EACCES(Permission denied)

  

imgBitmap = MediaStore.Images.Media.getBitmap(cr,selectedImage);

这是方法onActivityResult()

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case CAMERA_REQUEST:
                if (resultCode == Activity.RESULT_OK){
                    Uri selectedImage = imageUri;
                    getActivity().getContentResolver().notifyChange(selectedImage, null);
                    ContentResolver cr = getActivity().getContentResolver();
                    Bitmap imgBitmap;
                    try {
                        imgBitmap = MediaStore.Images.Media.getBitmap(cr, selectedImage);

                        accountPhoto.setImageBitmap(imgBitmap);
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(getActivity().getApplicationContext(), "Something went wrong while taking a photo", Toast.LENGTH_LONG).show();
                        Log.e("Camera", e.toString());
                    }

                }
        }
    }

我阅读了有关此EACCES的一些相关问题和解决方案,似乎问题出在我的允许之下:

<uses-feature android:name="android.hardware.camera2" android:required="true"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
我错过了什么吗?谢谢你回复

2 个答案:

答案 0 :(得分:2)

您必须在开始说明之前请求许可,因为此许可在Marshmallow中被认为是危险的:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && 
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) 
     {
      requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, RESULT);
     } 
    else
     {
    //your code
     }

答案 1 :(得分:0)

我怀疑WRITE_EXTERNAL_STORAGE会覆盖READ_EXTERNAL_STORAGE读取权限。如果你查看documentation,你会发现前者也允许从存储中读取。

尝试删除android:maxSdkVersion属性,看看是否有效。我怀疑您的设备运行的是SDK版本&gt; 18.

查看此答案以获取更多信息:https://stackoverflow.com/a/15270626/425238