Android check permission

18,361

Solution 1

My question is what's the difference between above these codes?

None, on API 23(+) devices.

Devices running an older version of Android, however, will generate an error through when you try to call context.checkSelfPermission() directly. This method wasn't available until API 23.

ContextCompat provides a backwards compatible way to run checkSelfPermission() on older APIs too. If you look at the implementation, you'll see it accomplishes this by simply delegating the call to checkPermission() with the app's own process parameters. checkPermission() has been available since very first API release and will thus work across the board.

public static int checkSelfPermission(@NonNull Context context, @NonNull String permission) {
    if (permission == null) {
        throw new IllegalArgumentException("permission is null");
    }

    return context.checkPermission(permission, android.os.Process.myPid(), Process.myUid());
}

which is the correct way to check for permission granted or not?

So, to answer this question: if you're only supporting devices running Android 'Marshmallow' 6.0 and newer, then you can use either approach. However, since it's more likely you also want to support some older versions of Android, use ContextCompat.

Solution 2

Coding on the official and recent way for supporting in all devices use below snippet

Request the permissions you need

 // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(thisActivity,
                    Manifest.permission.READ_CONTACTS)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
                Manifest.permission.READ_CONTACTS)) {

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

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

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }

Handle the permissions request response

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

Solution 3

Add This Code To Gradle

implementation 'com.karumi:dexter:5.0.0'

and Add This Code To Your Code

Dexter.withActivity(getActivity()).withPermission(Manifest.permission.CAMERA).withListener(
                            new PermissionListener() {
                                @Override
                                public void onPermissionGranted(PermissionGrantedResponse response) {
                                  YourCode
                                }

                                @Override
                                public void onPermissionDenied(PermissionDeniedResponse response) {

                                }

                                @Override
                                public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {

                                }
                            }
                    ).check();
Share:
18,361
Madhukar Hebbar
Author by

Madhukar Hebbar

JAVA/Android developer in telecom domain

Updated on June 13, 2022

Comments

  • Madhukar Hebbar
    Madhukar Hebbar almost 2 years

    I am developing my project in SDK version 23 where app permissions were newly introduced. In some guidelines they were using below code to read phone state permission is granted or not

    if (ContextCompat.checkSelfPermission(serviceContext, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
        //Read Phone state
       }else{
    }
    

    But i am directly accessing checkSelfPermission like below

    if(serviceContext.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
          //Read Phone state
       }else{
    }
    

    It's working fine. My question is what's the difference between above these codes?.which is the correct way to check for permission granted or not?

  • Madhukar Hebbar
    Madhukar Hebbar over 8 years
    Thanks. i will use it:)
  • Madhukar Hebbar
    Madhukar Hebbar over 8 years
    Thanks @Anoop . I got the answer.