我可以选择以下任一方法来检查我的应用是否具有给定权限。
哪一个是首选?
ContextCompat
(来自 support-compat
库):
ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
或者 PermissionChecker
(来自 support-core-utils
库):
PermissionChecker.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
请注意(自 25.3.1 起)-core-utils 取决于 -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 (*)
最佳答案
进入PermissionChecker
的源代码,我们可以看到它首先调用了Context#checkPermission
。如果调用代码没有权限,则提前退出。如果调用代码确实有权限,它就会转到神秘的 AppOpsManager
。问我们有没有permissionToOp
,然后检查 noteProxyOp
的返回值.这给了我们关于此方法的用途的提示,因为 noteProxyOp
的文档以:
Make note of an application performing an operation on behalf of another application when handling an IPC.
此外,如果我们检查 PermissionChecker
方法的返回值,我们会看到我们得到了 3 种可能结果之一:
The permission check result which is either
PERMISSION_GRANTED
orPERMISSION_DENIED
orPERMISSION_DENIED_APP_OP
.
即 0、-1 或 -2 返回值。此类似乎旨在供接收进程间通信并代表其他应用执行操作的应用使用。
ContextCompat
另一方面,简单地抓取当前进程ID并直接返回Context#checkPermission
的结果:
PERMISSION_GRANTED
if the given pid/uid is allowed that permission, orPERMISSION_DENIED
if it is not.
因此对于大多数编写标准 Android 应用程序的开发人员来说,使用 ContextCompat
。
关于android - 我应该更喜欢 ContextCompat 还是 PermissionChecker 在 Android 上进行权限检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44813943/