Search code examples
androidpermissionsandroid-manifest

How i can request permission at runtime in Android?


I'm developing an Android application, I have to allow users to use camera to scan a QRCode.

In each Android version (except > 6.0) i haven't problem, but in marshmallow I must enable manually the permission from "Settings -> App ->Permission" (it's strange because I have declared the camera permission in the manifest).

I read the documentation dev-android website but i don't understand some things:

if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {

        } else {    
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

    }
}

Second part of the code:

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

How i can adapt this code to my problem ?

What is "MY_PERMISSIONS_REQUEST_READ_CONTACTS" ?


Solution

  • MY_PERMISSIONS_REQUEST_READ_CONTACTS is a static int variable that you need to set in your Activity. It is the request code that is used in onRequestPermissionsResult. It is required so that you know which permission was acted upon (whether it be accepted or rejected) in onRequestPermissionsResult.

    At the top of your Activity just put private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1; (the number can be whatever you want)