在Android版本7中运行时权限

时间:2017-05-05 05:18:57

标签: android permissions

我正在使用此代码获取android marshmallow中的运行时权限,但它在Android 7及以上版本中无效

int PERMISSION_ALL = 123;
String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_SMS, Manifest.permission.CAMERA,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE};

if (!hasPermissions(HomeActivity.this, PERMISSIONS)) {
    ActivityCompat.requestPermissions(HomeActivity.this, PERMISSIONS, PERMISSION_ALL);
}

public static boolean hasPermissions(Context context, String... permissions
{
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }

    return true;
}

1 个答案:

答案 0 :(得分:0)

试试这个

int PERMISSION_ALL = 123;
String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_SMS, Manifest.permission.CAMERA,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE};

        if (!hasPermissions(HomeActivity.this, PERMISSIONS)) {
            requestPermissions(PERMISSIONS, PERMISSION_ALL);
        }

    public static boolean hasPermissions(Context context, String... permissions) {
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
                for (String permission : permissions) {
                    if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                        return false;
                    }
                }
            }
            return true;
        }

请使用requestPermision(permissions,PERMISSION_ALL);代替ActivityCompat.requestPermision(context,permissions,PERMISSION_ALL);