解决open failed: EACCES (Permission denied)

时间:2022-07-16 22:58:41

在开发项目中,遇见要进行文件操作,遇见Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)错误

网上的解决办法有添加权限:

 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
但是在添加权限之后发现还是报错,之后看到一篇大神的文章才发现,android 6.0之上的系统除了添加权限还要在你报错的代码前面添加请求权限的代码。

private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
   Manifest.permission.READ_EXTERNAL_STORAGE,
   Manifest.permission.WRITE_EXTERNAL_STORAGE };

public static 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);
      }
   }