I can choose from either of the following ways of checking to see if my app has a given permission.
Which one is preferred?
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 (*)
Stepping into the source of PermissionChecker
we can see that it first calls through to Context#checkPermission
and bails early if the calling code does not have permission. If the calling code does have permission it then goes to the mysterious AppOpsManager
asking if we have permissionToOp
, followed by a check against the return of noteProxyOp
. This gives us a hint about what this method is for, since the docs for noteProxyOp
start with:
Make note of an application performing an operation on behalf of another application when handling an IPC.
Additionally, if we check the return value of the PermissionChecker
method we see we get back one of 3 possible results:
The permission check result which is either
PERMISSION_GRANTED
orPERMISSION_DENIED
orPERMISSION_DENIED_APP_OP
.
That is, 0, -1 or -2 return values. This class appears to be intended for use by apps receiving inter-process communication and performing actions on behalf of other apps.
ContextCompat
on the other hand, simply grabs the current process ID and directly returns the result of Context#checkPermission
:
PERMISSION_GRANTED
if the given pid/uid is allowed that permission, orPERMISSION_DENIED
if it is not.
So for most developers writing standard Android apps, use ContextCompat
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With