Search code examples
androidpermissionsandroid-manifestandroid-6.0-marshmallowruntime-permissions

Can I use checkPermission instead of checkSelfPermission on android +24?


According to this document,

to check if you have a permission, call the ContextCompat.checkSelfPermission()

And this document says:

[Context].checkPermission() is to determine whether the given permission is allowed for a particular process and user ID running in the system

I've the following code on android 24:

smsPerm = "android.permission.SEND_SMS";
int result = checkPermission(smsPerm, Process.myPid(), Process.myUid());

the result would be:

  • PackageManager.PERMISSION_GRANTED if smsPerm is added to manifest and is granted on runtime.
  • PackageManager.PERMISSION_DENIED if smsPerm is added to manifest but is not granted on runtime.
  • PackageManager.PERMISSION_DENIED if smsPerm is not added to manifest.

With that saying, it seems the behavior is the same as checkSelfPermission on android +24. Can I use checkPermission instead of checkSelfPermission?


Solution

  • I am uncertain what you think you are gaining... but, yes, you can use Context#checkPermission() instead of ContextCompat.checkSelfPermission().

    The implementation of ContextCompat.checkSelfPermission() uses Context#checkPermission(), at least at the time that I posted this answer.

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

    For the long term, it would be safer to use ContextCompat.checkSelfPermission(). That can be updated to reflect new rules applied in new versions of Android.