Should I use ContextCompat or PermissionChecker to check Android permissions?
I can select one of the following verification methods to see if my application has this permission.
Which one is preferable?
ContextCompat
(from support-compat
lib):
ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
Or PermissionChecker
(from support-core-utils
lib):
PermissionChecker.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
Note that (as of 25.3.1) -core-utils depends on -compat:
| | +--- com.android.support:support-core-utils:25.3.1
| | | +--- com.android.support:support-annotations:25.3.1
| | | \--- com.android.support:support-compat:25.3.1 (*)
source to share
In the original state, PermissionChecker
we can see that it calls first Context#checkPermission
and is released earlier if the calling code has no permission. If the calling code has permission, it goes to the mysterious one AppOpsManager
asking if we have permissionToOp
, and then checking for a return noteProxyOp
. This gives us a hint as to what this method is for, since the docs for noteProxyOp
start with:
Notice the application performing the operation on behalf of another application while processing IPC.
Additionally, if we inspect the return value of the method PermissionChecker
, we see that we are returning one of three possible results:
Permission check result, which is either
PERMISSION_GRANTED
, or,PERMISSION_DENIED
orPERMISSION_DENIED_APP_OP
.
That is, 0, -1, or -2 will return values. This class appears to be intended for use by applications that receive interprocess communication and perform actions on behalf of other applications.
ContextCompat
, on the other hand, just grabs the current process id and returns the result Context#checkPermission
:
PERMISSION_GRANTED
if the given pid / uid is allowed this permission, orPERMISSION_DENIED
if it is not.
So for most developers writing standard Android apps, useContextCompat
.
source to share
I will go with ContextCompat
because of the documentation and the quality of the tutorials available
But I read something:
If your device is running Android M and above and the targetSdkVersion is below 22, there is a slight difference between the two.
When you launch the app for the first time with the device permission disabled, the behavior looks like this:
- ContextCompat: always returns GRANTED
- PermissionChecker: Returns GRANTED or PERMISSION_DENIED_APP_OP
It PermissionChecker
might be wiser with this usage , but again you need to set targetSdkVersion to 23 or higher to implement runtime permissions.
source to share