gpt4 book ai didi

android - shouldShowRequestPermissionRationale 未按预期工作

转载 作者:太空宇宙 更新时间:2023-11-03 11:00:03 30 4
gpt4 key购买 nike

我正在检查并获得 API 级别 23 及更高级别用户的许可。所以这对我来说是一件令人困惑的事情,android.com 说:

shouldShowRequestPermissionRationale() method returns true if the app has requested this permission previously and the user denied the request. If the user turned down the permission request in the past and chose the Don't ask again option in the permission request system dialog, this method returns false

另一方面,它给出了以下代码,用于检查权限并在需要时请求权限

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?
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, we can 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.
}
}

else 如果用户不允许权限并检查 Don't Ask Again,则上面示例中的范围将运行,对吗?因此,使用此代码,用户在第一次运行时永远不会被要求获得许可。我测试了该代码,结果符合我的预期。那么,如果用户之前拒绝了我的请求,我该如何请求第一次运行的权限并做某事,如果用户拒绝我的请求并选中不再询问,我该如何做?

最佳答案

您可以执行以下操作。

  1. 每次都通过检查权限是否尚未授予来请求权限。不要在该方法中处理“不再询问”。 (如果用户勾选“Don't ask again”,操作系统会自动处理,不会再请求权限,会回调权限被拒绝)
  2. 在回调方法 onRequestPermissionsResult() 中处理 ActivityCompat.shouldShowRequestPermissionRationale()

这是我每次都在请求许可的代码

public void checkAndAskCameraPermission() {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(context,
new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_ID);
}
}

我是这样处理回电的

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case CAMERA_PERMISSION_REQUEST_ID: {
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {

// Do something if permission is not granted and the user has also checked the **"Don't ask again"**
} else if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
// Do something if permission not granted
}
}
}
}

关于android - shouldShowRequestPermissionRationale 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46040141/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com