Android如何使用shouldShowRequestPermissionRationale判断权限状态
根据官方文档说明,shouldShowRequestPermissionRationale方法用于判断是否需要向用户展示权限申请理由的UI。

实际测试发现以下两种场景下该方法都会返回false:
- 将某权限设置为“Notify”状态,且从未弹出过权限申请弹窗时
- 用户拒绝权限时勾选了“Never ask again”选项时
针对衍生的两个问题,解答如下:
1. 如何区分上述两种返回false的场景
你可以在应用本地通过持久化标记(比如SharedPreferences)记录是否已经向用户发起过对应权限的申请,结合方法返回结果即可区分:
- 若方法返回false,且本地无该权限的申请记录,属于从未申请过的Notify状态
- 若方法返回false,且本地已有该权限的申请记录,属于用户勾选了“永不询问”的拒绝状态
2. 用户勾选“Never ask again”时,官方示例代码是否会调用requestPermissions方法
官方示例代码如下:
if (ContextCompat.checkSelfPermission( CONTEXT, Manifest.permission.REQUESTED_PERMISSION) == PackageManager.PERMISSION_GRANTED) { // You can use the API that requires the permission. performAction(...); } else if (shouldShowRequestPermissionRationale(...)) { // In an educational UI, explain to the user why your app requires this // permission for a specific feature to behave as expected. In this UI, // include a "cancel" or "no thanks" button that allows the user to // continue using your app without granting the permission. showInContextUI(...); } else { // You can directly ask for the permission. requestPermissions(CONTEXT, new String[] { Manifest.permission.REQUESTED_PERMISSION }, REQUEST_CODE); }
答案是会调用。此时权限未授权,shouldShowRequestPermissionRationale返回false,会直接走到else分支执行requestPermissions。只是此时系统不会弹出权限申请弹窗,会直接向onRequestPermissionsResult返回PERMISSION_DENIED的结果。
内容的提问来源于stack exchange,提问作者mianlaoshu
相关产品推荐
相关产品推荐

