xRobot xRobot - 26 days ago 18
Android Question

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;
}
}
}

Answer

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().

Comments