Android 6.0以后的版本报错:open failed: EACCES (Permission denied)
在开发项目中,遇见要进行文件操作,遇见Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)错误 .
此问题共分为三步来解决:
首先来说下联网和读写文件问题:
1.添加权限(注意:6.0后的版本即使添加了权限还是会报错,但是权限声明是必须要加的)
AndroidManifest.xml中添加权限:
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2.添加了联网权限后还是连不上网,或者联网拒绝,这里四种解决办法:
a.APP改用https
b.targetSdkVersion 降到27以下
c.AndroidManifest.xml中的application加入:
- <application
- android:usesCleartextTraffic="true" //这个是需要加入的内容,可以解决联网访问路径问题 ..... >
d.c中比较复杂的写法:在res下创建xml文件夹,在xml文件夹中在建立network_security_config.xml文件,内容如下:
network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true" /> </network-security-config>
然后在AndroidManifest.xml的application标签中加入:
android:networkSecurityConfig="@xml/network_security_config"
3.此时还是会报无法存储的问题,这里是因为6.0后的权限需要手动申请,我们需要在MainActivity中加入如下的代码:
- private final int REQUEST_EXTERNAL_STORAGE = 1;
- private String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; public void verifyStoragePermissions(Activity activity) { // Check if we have write permission int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { // We don't have permission so prompt the user ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE); } }
然后我们在onCreate方法中引用即可:
verifyStoragePermissions(this);