检查android设备中app的运行时权限

时间:2016-11-28 13:23:09

标签: java android android-permissions

我正在使用以下代码片段来理解用户设置的权限,因为在较新的Android设备中,可以从设置中调整特定应用的权限。

我想提醒用户提供权限以避免应用程序崩溃但以下代码段始终为我返回true。我做错了什么?

//If authorisation not granted for camera
boolean permission = (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED);


if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
    //ask for authorisation
    //Manifest.permission.CAMERA
    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
            Manifest.permission.CAMERA)) {
        showExplanation("Permission Needed", "Rationale", Manifest.permission.CAMERA, REQUEST_PERMISSION_CAMERA);
    }
    else
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_PERMISSION_CAMERA);
}
else
    try {
        //releasing camera if it's already in use
        releaseCamera();
        camera = Camera.open(camId);
}catch (Exception e)
{
    e.printStackTrace();
}

2 个答案:

答案 0 :(得分:1)

boolean permission = (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED);

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
    //ask for authorisation
    //Manifest.permission.CAMERA
    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
            Manifest.permission.READ_PHONE_STATE)) {
        showExplanation("Permission Needed", "Rationale", Manifest.permission.READ_PHONE_STATE, REQUEST_PERMISSION_CAMERA);
    }
    else
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_PERMISSION_CAMERA);
}
else{
    try {
        //releasing camera if it's already in use
        releaseCamera();
        camera = Camera.open(camId);
}catch (Exception e)
{
    e.printStackTrace();
}}   /////// put your else condition in braces

答案 1 :(得分:0)

我遇到了这个问题,因为此功能仅在api level 23及更高版本中可用。我在22岁时编译。