血的教训 关于6.0的读取权限问题

本来做的头像设置的功能好好的(读取sd文件),可是当运行在华为5C(6.0)上时,马丹,不可行。

        String path = Environment.getExternalStorageDirectory().getPath()+ "/head.png";
        if(!path.equals("")){
            Bitmap b = BitmapFactory.decodeFile(path);
            if (b != null){
                find_img_head.setImageBitmap(b);
            }
        }

报的这个错!

E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/head.png: open failed: EACCES (Permission denied)

打印这个方法检测能否读取:

        File sd = Environment.getExternalStorageDirectory();
        boolean can_write = sd.canWrite();
        Log.e("tag","can_write:"+can_write);

当然是false。


可是我权限都加了呀  

android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

最后才知道在6.0不光要在mainfest中加上上面两个权限,还要在Activity中加上权限,调用这个方法即可。

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


2016.7.6添加6.0定位的权限:

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET,
            Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS};

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.ACCESS_FINE_LOCATION);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }


你可能感兴趣的:(血的教训 关于6.0的读取权限问题)