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

android 6.0以上读写权限(需要手动配置)

程序员文章站 2022-05-14 21:34:23
...

错误提示:   W/System.err:   java.io.IOException:Permission denied 

1.首先,在manifest中加入permission 

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

2.然后,新建一个permission工具类,在其中定义所需权限。这里只需要读写,因此只把读写加入进去,如果需要更多的权限,加入即可。

public class PermisionUtils {
// Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE =1;
    private static String[]PERMISSIONS_STORAGE = {
    Manifest.permission.READ_EXTERNAL_STORAGE,
    Manifest.permission.WRITE_EXTERNAL_STORAGE};
/**
* Checks if the app has permission to write to device storage
* If the app does not has permission then the user will be prompted to
* grant permissions
*
     * @param activity
     */
    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);
        }
    }
}

3.然后,在Activity中调用即可。

public class MainActivity extends AppCompatActivity {
    @Override
     protected void onCreate(Bundle savedInstanceState) {    
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main); 
          verifyStoragePermissions(this);
    }
}

参考记录:

解决设置Android 23.0以上版本对SD卡的读写权限无效的问题

https://blog.csdn.net/wjb820728252/article/details/74159535

相关标签: permission