我想请求运行时的权限。我查看了官方的 Android 开发者网站,它说如果权限之前被拒绝,则
shouldShowRequestPermissionRationale
返回 true;如果权限被拒绝,则返回 false,并且选择了不再询问复选框。
然后我在网站上看到了这段代码:
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 个问题是:
如果之前未征得用户许可,会发生什么情况?我们需要询问用户,对吗?你把代码放在哪里?
即使用户选中了“不再询问”复选框,上面的代码也会请求许可(当
shouldShowRequestPermissionRationale
返回 false 时,即在 else 块中)。当用户选中该选项时,您如何请求许可?
回答你的两个问题:
您可以先使用
checkSelfPermission()
查看权限是否已被授予。如果尚未授予,那么您应该检查 shouldShowRequestPermissionRationale()
是否返回 true 或 false。
shouldShowRequestPermissionRationale()
在以下情况下将返回 true:
shouldShowRequestPermissionRationale()
在以下两种情况下将返回 false:
所以,你能做的是,如果
shouldShowRequestPermissionRationale()
返回 false
您可以使用布尔首选项值(默认值为 true)来检查
else情况下第一次请求许可,如果是第一次 请求,然后触发
requestPermissions
否则,如果这不是第一个请求,并且用户之前拒绝了该请求,并且选中了“不再询问”复选框,则您可以显示一个简单的 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
}
}