xRobot
xRobot

Reputation: 26567

How to grant permission for the camera?

I just need a way to get permission for using the camera of the smartphone. I wrote this code, but the permission request dialog doesn't appear.

in the onCreate:

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA}, 1);
        }
    }

}



@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // my code after granted permission

            } else {


            }
            return;
        }
    }
}

Upvotes: 0

Views: 640

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006584

requestPermissions() is not called because "ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)" is true

Step #1: Show some rationale (dialog, snackbar, something inline in your UI, whatever)

Step #2: When the user taps on something specific in that rationale UI (e.g., OK button), call requestPermissions()

Or, if you do not want to show rationale for why you are requesting the permission, do not call shouldShowRequestPermissionRationale().

Upvotes: 1

Related Questions