Android运行时权限无效

时间:2017-03-21 15:04:44

标签: android permissions camera android-camera runtime-permissions

这是我在Android中询问运行时CAMERA权限的代码。我从handleCameraPermission()致电onCreate()

当我第一次运行我的应用时,会自动启用该权限。我去了设置并禁用了权限。但是checkIfPermissionEnabled()仍然返回true,但相机无法启动。那么,checkIfPermissionEnabled()会出现什么问题?

当我设置hasCameraPermission = false并执行代码时,没有对话框但相机权限已启用且一切正常。

private boolean checkIfPermssionEnabled() {
    int result = ContextCompat.checkSelfPermission(context, android.Manifest.permission.CAMERA);
    if(result == PackageManager.PERMISSION_GRANTED)
        return true;
    return false;
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case CAMERA_PERMISSION_REQUEST:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //granted
                hasCameraPermission = true;
            } else {
                //not granted
                hasCameraPermission = false;
                super.onBackPressed();
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

private void handleCameraPermission() {
    int myVersion = Build.VERSION.SDK_INT;
    if(myVersion >= Build.VERSION_CODES.M) {
        hasCameraPermission = checkIfPermssionEnabled();
        if(!hasCameraPermission) {
            Log.d("cam","cam no permission");
            //if(ActivityCompat.shouldShowRequestPermissionRationale(activity,android.Manifest.permission.CAMERA)) {
                ActivityCompat.requestPermissions(activity,new String[]{android.Manifest.permission.CAMERA},CAMERA_PERMISSION_REQUEST);
                Log.d("cam","cam dialog permission showed");
            }
            //else {
            //  ActivityCompat.requestPermissions(activity, new String[]{android.Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST);
            //}
        } else
            Log.d("cam","cam has permission");
    } else
        hasCameraPermission = true;
}

我想要实现的是,如果未启用相机权限,则应显示询问权限的默认对话框,我应该收到用户输入的回调,即获得通知是用户按下拒绝或允许。

1 个答案:

答案 0 :(得分:0)

您忘记以这种方式询问权限:

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, YOUR_REQUEST_CODE);