欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android6.0以上文件读写问题

程序员文章站 2022-05-20 10:26:01
...
在开发项目中,遇见要进行文件操作,遇见Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)错误(如下权限已经添加)
<uses-permission android:name="android.permission.WRITE_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);
      }
   }

使用时,直接调用verifyStoragePermissions函数