根据Google的说法,当谈到M Developer Preview运行时权限时:
但是,我们只有一种方法,shouldShowRequestPermissionRationale()
,返回boolean
,我们有三种状态。我们需要一种方法来区分永不问状态和停止询问状态,因为我们从false
得到shouldShowRequestPermissionRationale()
两者。
对于首次运行应用程序时请求的权限,这不是一个大问题。有很多方法可以确定这可能是您的应用程序的第一次运行(例如,boolean
中的SharedPreferences
值),因此您假设如果它是您的应用程序的第一次运行,那么您处于从未问过的状态。
但是,运行时权限的一部分愿景是您可能不会事先要求所有这些权限。当用户点击需要该权限的内容时,您可能只会在稍后要求的边缘功能上绑定权限。在这里,应用程序可能已运行多次,持续数月,之后我们突然需要请求另一个权限。
在这些情况下,我们是否应该跟踪我们是否自己要求获得许可?或者Android M API中是否有我遗漏的东西告诉我们之前是否询问过?
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == REQUEST_CAMERA) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
doThing();
//STORE FALSE IN SHAREDPREFERENCES
} else {
//STORE TRUE IN SHAREDPREFERENCES
}
}
在SharedPreferences中存储一个布尔值,使用key作为您的权限代码和值,如上所示,以指示之前是否已拒绝该首选项。
遗憾的是,您可能无法检查已在应用程序运行时已被接受并稍后被拒绝的首选项。最终规范不可用,但您的应用程序有可能重新启动或获取模拟值,直到下次启动。
我知道我发帖很晚,但详细的例子可能对某人有帮助。
我注意到的是,如果我们在onRequestPermissionsResult()回调方法中检查shouldShowRequestPermissionRationale()标志,它只显示两个状态。
状态1: - 返回true: - 用户单击拒绝权限(包括第一次)。
状态2:-Returns false: - 如果用户选择s“永远不会再问。
以下是具有多个权限请求的示例: -
该应用程序在启动时需要2个权限。 SEND_SMS和ACCESS_FINE_LOCATION(在manifest.xml中都提到了)。
应用启动后,它会一起请求多个权限。如果两个权限都被授予,则正常流程会进行。
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(checkAndRequestPermissions()) {
// carry on the normal flow, as the case of permissions granted.
}
}
private boolean checkAndRequestPermissions() {
int permissionSendMessage = ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS);
int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (locationPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.SEND_SMS);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
如果未授予一个或多个权限,activityCompat.requestPermissions()将请求权限,控件将转到onRequestPermissionsResult()回调方法。
您应该在onRequestPermissionsResult()回调方法中检查shouldShowRequestPermissionRationale()标志的值。
只有两种情况: -
案例1: - 任何时间用户点击拒绝权限(包括第一次),它将返回true。因此,当用户拒绝时,我们可以显示更多解释并再次询问。
案例2: - 只有当用户选择“永不再问”时,它才会返回false。在这种情况下,我们可以继续使用有限的功能并指导用户从设置中激活权限以获得更多功能,或者我们可以完成设置,如果权限对于应用程序来说是微不足道的。
情况1
案例-2
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
Log.d(TAG, "Permission callback called-------");
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<>();
// Initialize the map with both permissions
perms.put(Manifest.permission.SEND_SMS, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
// Fill with actual results from user
if (grantResults.length > 0) {
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for both permissions
if (perms.get(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "sms & location services permission granted");
// process the normal flow
//else any one or both the permissions are not granted
} else {
Log.d(TAG, "Some permissions are not granted ask again ");
//permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission
// // shouldShowRequestPermissionRationale will return true
//show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.SEND_SMS) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
showDialogOK("SMS and Location Services Permission required for this app",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.
break;
}
}
});
}
//permission is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG)
.show();
// //proceed with logic by disabling the related features or quit the app.
}
}
}
}
}
}
private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener)
.create()
.show();
}
不,您不需要跟踪是否要求获得许可,并且您不需要区分Never-Asked和Stop-Asking。
对于应用程序开发人员,状态1和3是相同的:您需要权限和ActivityCompat.checkSelfPermission != PackageManager.PERMISSION_GRANTED
,然后只要用户点击需要权限的功能,无论您请求了多少次,您都可以通过ActivityCompat.requestPermissions()
请求权限。用户最终将“授予”它,或者“拒绝”它,并且“再也不要再问”。该设计不会阻止您多次弹出权限请求对话框。
但是,设计确实鼓励您在某些时候解释许可的目的 - 您的州2. shouldShowRequestPermissionRationale()
不用于确定您是否应该请求许可,它用于确定您是否应该在您请求许可之前显示解释。
关于州3的更多解释:
shouldShowRequestPermissionRationale()
的原因。ActivityCompat.requestPermissions()
将不再弹出对话框。shouldShowRequestPermissionRationale()
返回false后禁用UI。我有一个方法来解决你的问题,它似乎对我很好。
我使用SharedPreferences来区分Never-Asked from Stop-Asking,我将举例说明我如何使用它。
private void requestAccountPermission() {
SharedPreferences mPreferences = getSharedPreferences("configuration", MODE_PRIVATE);
boolean firstTimeAccount = mPreferences.getBoolean("firstTimeAccount", true);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.GET_ACCOUNTS)) {
// 2. Asked before, and the user said "no"
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.GET_ACCOUNTS}, REQUEST_CODE_ACCOUNTS);
}else {
if(firstTimeAccount) {
// 1. first time, never asked
SharedPreferences.Editor editor = mPreferences.edit();
editor.putBoolean("firstTimeAccount", false);
editor.commit();
// Account permission has not been granted, request it directly.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.GET_ACCOUNTS},REQUEST_CODE_ACCOUNTS);
}else{
// 3. If you asked a couple of times before, and the user has said "no, and stop asking"
// Your code
}
}
}
这是跟踪第一次显示权限对话框的时间,用户选中永不再询问的方法以及用户检查后直接拒绝权限的方法从不再问这个问题我们需要保留一个标记,如果在获得权限理由对话框之前导致onRequestPermissionsResult。需要时调用方法checkPermission()。
public boolean mPermissionRationaleDialogShown = false;
public void checkPermission() {
if (ContextCompat.checkSelfPermission(this, "PermissionName")
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, "PermissionName")) {
showPermissionRequiredDialog();
} else {
askPermission();
}
} else {
// Permission Granted
}
}
public void askPermission() {
ActivityCompat.requestPermissions(this,
new String[]{"PermissionName"}, permissionRequestCode);
}
public void showPermissionRequiredDialog() {
mPermissionRationaleDialogShown = true;
// Dialog to show why permission is required
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, "PermissionName")
&& !mPermissionRationaleDialogShown) {
// Permission dialog was shown for first time
} else if (ActivityCompat.shouldShowRequestPermissionRationale(this, "PermissionName")
&& mPermissionRationaleDialogShown){
// User deny permission without Never ask again checked
} else if (!ActivityCompat.shouldShowRequestPermissionRationale(this, PERMISSION_READ_EXTERNAL)
&& mPermissionRationaleDialogShown) {
// User has checked Never ask again during this permission request
} else {
// No permission dialog shown to user has user has previously checked Never ask again. Here we can show dialog to open setting screen to change permission
}
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
在这里尝试了所有的答案和互联网上的其他一些帖子。我开始知道我必须使用sharedPreference isLocationPermissionDialogShown
(默认为false),并且所有内容都按预期工作。
shouldShowRequestPermissionRationale
返回false
和isLocationPermissionDialogShown
也false
shouldShowRequestPermissionRationale
返回true
,在显示对话框时,我们将isLocationPermissionDialogShown
设置为true
。当我们检查条件时,两者都将是true
shouldShowRequestPermissionRationale
返回true
和isLocationPermissionDialogShown
返回true
shouldShowRequestPermissionRationale
返回false
和isLocationPermissionDialogShown
返回true
。这就是我们需要的。请查看工作示例。
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
String locationPermission;
String prefLocationPermissionKey = "isLocationPermissionDialogShown";
private final int PERMISSION_REQUEST_CODE_LOCATION = 1001;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationPermission = Manifest.permission.ACCESS_FINE_LOCATION;
sharedPreferences = getSharedPreferences("configuration", MODE_PRIVATE);
//check for android version
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//Check for permission
if (checkSelfPermission(locationPermission) != PackageManager.PERMISSION_GRANTED) {
//check if clarification dialog should be shown.
if (shouldShowRequestPermissionRationale(locationPermission)) {
showClarificationDialog(locationPermission, PERMISSION_REQUEST_CODE_LOCATION);
} else {
requestPermissions(new String[] { locationPermission}, PERMISSION_REQUEST_CODE_LOCATION);
}
} else {
Log.d("nets-debug", "permission already grranted");
}
}
}
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
//for location permission
if (requestCode == PERMISSION_REQUEST_CODE_LOCATION) {
boolean isLocationPermissionDialogShown = sharedPreferences.getBoolean(prefLocationPermissionKey, false);
if (!shouldShowRequestPermissionRationale(locationPermission) && isLocationPermissionDialogShown) {
// user selected Never Ask Again. do something
Log.d("nets-debug", "never ask again");
} else {
// all other conditions like first time asked, previously denied etc are captured here and can be extended if required.
Log.d("nets-debug", "all other cases");
}
}
}
}
@TargetApi(Build.VERSION_CODES.M)
public void showClarificationDialog(final String permission, final int requestCode) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Permission Required");
builder.setMessage("Please grant Location permission to use all features of this app");
builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(prefLocationPermissionKey, true);
editor.apply();
requestPermissions(new String[] {permission}, requestCode);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "This permission required", Toast.LENGTH_LONG).show();
}
});
builder.create().show();
}
}
希望这会有所帮助。
所以我的时间最终还是要回答公司的问题
业务流程: -
1.当用户第一次点击“拒绝权限”时,我将显示理由对话框以解释权限的必要性。然后,如果用户点击理由对话框中的“取消”按钮,我将显示一个祝酒词,显示消息“请给予获取位置的权限”。
2.之后当用户点击权限对话框上的拒绝权限(不要再问)时,我会显示一条消息“请从应用程序设置中获取位置权限”。请注意,我添加了“来自应用设置”的字样,因为用户已经选中了“不要再问”的方框。
3.因此,从现在开始,将不会显示权限对话框。此外,不会显示基本原理对话框。
因此,关键是如果未显示权限对话框和基本原理对话框,则表示用户已选中“不要再询问”复选框。
代码:-
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_FINE_LOCATION)){
AlertDialogHelper.showDialogWithYesNoCallback(mContext, getString(R.string.confirm), getString(R.string.please_give_permission_to_get_location), new onItemClickReturnBoolean() {
@Override
public void onItemClick(Boolean status) {
if(status){
ActivityCompat.requestPermissions(SplashScreenActivity.this,permissions,AppConfig.FINE_LOCATION_PERMISSION_REQUEST_CODE);
}
else{
ShowToast.showShortToast(SplashScreenActivity.this,getString(R.string.please_give_permission_to_get_location));
finish();
}
}
});
}
else{
ActivityCompat.requestPermissions(this,permissions,AppConfig.FINE_LOCATION_PERMISSION_REQUEST_CODE);
}
}
else{
gettingLocationAfterPermissionGranted();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == AppConfig.FINE_LOCATION_PERMISSION_REQUEST_CODE){
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
gettingLocationAfterPermissionGranted();
}
else{
if(ActivityCompat.shouldShowRequestPermissionRationale(SplashScreenActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)){
ShowToast.showShortToast(this,getString(R.string.please_give_permission_to_get_location));
}
else{
ShowToast.showShortToast(this,getString(R.string.please_give_location_permission_from_app_settings));
}
finish();
}
}
}
检查此存储库:https://github.com/debChowdhury/PermissionHelperEasy
Easy peasy
你可以看看here - 有一个流程图可以很好地解释这个过程。它还解释了何时应该调用shouldShowRequestPermissionRationale()
以及何时返回true。
基本上根据Android的文档,如果你没有它,你应该总是请求许可(如果用户说永远不再询问,Android将在回调中自动返回DENIED)如果用户已经拒绝,你应该显示一条短消息你曾经过去,但没有标记永不再问的选项。
不需要为权限状态创建并行持久状态,您可以使用此方法随时返回当前权限状态:
@Retention(RetentionPolicy.SOURCE)
@IntDef({GRANTED, DENIED, BLOCKED})
public @interface PermissionStatus {}
public static final int GRANTED = 0;
public static final int DENIED = 1;
public static final int BLOCKED = 2;
@PermissionStatus
public static int getPermissionStatus(Activity activity, String androidPermissionName) {
if(ContextCompat.checkSelfPermission(activity, androidPermissionName) != PackageManager.PERMISSION_GRANTED) {
if(!ActivityCompat.shouldShowRequestPermissionRationale(activity, androidPermissionName)){
return BLOCKED;
}
return DENIED;
}
return GRANTED;
}
警告:在用户通过用户提示(在sdk 23+设备上)接受/拒绝权限之前,返回BLOCKED第一个应用程序启动