Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I prefer ContextCompat or PermissionChecker for permission checking on Android?

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 (*)

like image 205
Adam S Avatar asked Jun 28 '17 23:06

Adam S


1 Answers

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 or PERMISSION_DENIED or PERMISSION_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, or PERMISSION_DENIED if it is not.

So for most developers writing standard Android apps, use ContextCompat.

like image 91
Adam S Avatar answered Oct 25 '22 16:10

Adam S