shouldShowRequestPermissionRationale 方法的工作

Working of shouldShowRequestPermissionRationale method

我想在 runtime.I 上请求权限,查看了官方 android 开发者网站,它说 shouldShowRequestPermissionRationale returns 如果权限之前被拒绝则为真,如果之前被拒绝则 returns 为假权限已被拒绝并且不再询问复选框已选中。 然后我在网站上看到了这段代码:

if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {
        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
    } else {
        // No explanation needed; request the permission
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }

我的 2 个问题是:

1)如果之前没有征得用户许可会怎样?我们需要征得他同意吗?你把代码放在哪里了??

2)即使用户选中了不再询问复选框(当 shouldShowRequestPermissionRationale returns false,即在 else 块中,上面的代码也会请求许可)。当用户勾选了那个选项??

回答你的两个问题:

您可以先使用checkSelfPermission()查看权限是否已经被授予。如果没有被授予那么你应该检查 shouldShowRequestPermissionRationale() return 是对还是错。

在以下情况下,

shouldShowRequestPermissionRationale() 将 return 为真:

  • 当用户之前拒绝过权限但没有 选中 "Never Ask Again" 复选框。

shouldShowRequestPermissionRationale() 将 return 在以下两种情况下为 false:

  • 当用户之前拒绝了权限并且从不询问 再次选中复选框。
  • 当用户第一次请求权限时。

所以,你可以做的是,如果 shouldShowRequestPermissionRationale() returns false 您可以使用布尔首选项值(默认值为 true)来检查

  • else情况下第一次请求权限,如果是第一次 请求,然后触发 requestPermissions

  • else 如果这不是第一个请求并且用户之前拒绝了该请求并且还选中了 "Never ask again" 复选框,您可以显示一个简单的 toast 以及不可用的原因需要权限的功能,并提及通过设置手动启用它的步骤。

像这样:

    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
                Manifest.permission.READ_CONTACTS)) {
            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
        } else {
       if(isFirstTimeRequest){
            // No explanation needed; request the permission

            // RESET PREFERENCE FLAG

            ActivityCompat.requestPermissions(thisActivity,
                    new String[]{Manifest.permission.READ_CONTACTS},
                    MY_PERMISSIONS_REQUEST_READ_CONTACTS);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
          } else {
            // User denied previously and has checked "Never ask again"
            // show a toast with steps to manually enable it via settings
          }
        }