在Android M Error中读取外部存储权限

时间:2017-01-29 21:42:46

标签: android android-permissions

on onCreate Method

if (ContextCompat.checkSelfPermission(thisActivity,
            Manifest.permission.READ_EXTERNAL_STORAGE)
    != PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
        Manifest.permission.READ_EXTERNAL_STORAGE)) {


} else {

    ActivityCompat.requestPermissions(thisActivity,
            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            PERMISSION_REQUEST_CODE);
}

on onRequestPermissionsResult

@Override
public void onRequestPermissionsResult(int requestCode,
                                   String permissions[],int[]grantResults) {
switch (requestCode) {
    case PERMISSION_REQUEST_CODE: {

        if (grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            String path = Environment.getExternalStorageState();

        } else {

        }
        return;
    }
}

我努力了,但最终都以崩溃应用程序结束了。申请未获得许可。为什么?我做错了吗?感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我使用它作为我的代码,来自stackoverflow,但忘记了谁回答

public boolean hasPermission(Context context, String... permissions){
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    int PERMISSION_ALL = 1;
    String[] PERMISSIONS = {
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.CHANGE_NETWORK_STATE,
            Manifest.permission.WRITE_SETTINGS,
            Manifest.permission.CAMERA,
            Manifest.permission.RECEIVE_SMS,
            Manifest.permission.SEND_SMS,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_CONTACTS};
    public void checkAllPermission(){
        if (!hasPermission(getActivity(), PERMISSIONS)){
            ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, PERMISSION_ALL);
        }
    }
}

尝试(根据需要修改)