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

来源:互联网 发布:txt电子书软件下载 编辑:程序博客网 时间:2024/06/05 19:14

对Android的SD卡进行读取权限设置时:

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

结果报错:
这里写图片描述

依然提示我没有权限,于是百度说是版本问题,23.0版本(笔者的版本是25.0)以上的不仅仅要设置上面的权限,还要在对SD卡有读写操作的地方授权,下面是公共类:

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

然后直接在需要授权的地方调用:

    //检测读写权限    PermisionUtils.verifyStoragePermissions(this);

程序运行的时候,会询问是否授权

这里写图片描述

点击授权即可。