2017-09-04 136 views
1

我正在检查并获得API级别为23及以上的用户的许可。因此,这里是一个令人困惑的事情对我来说,android.com说:如果应用程序已请求此权限以前与用户拒绝了这一要求shouldShowRequestPermissionRationale未按预期工作

shouldShowRequestPermissionRationale()方法返回true。 如果用户拒绝了在过去的许可请求,并选择在许可请求的系统对话框中不要再次询问选项,这种方法在另一边返回false

它给检查的权限,并要求下面的代码如果neccessery

// 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范围在上面的例子中运行的权限,如果用户不允许许可和检查不要再次询问,对不对?因此,在第一次运行时,这个代码用户永远不会被要求获得许可。我测试了这个代码,结果就是我所期望的。 那么我怎么能要求第一次运行的权限,如果用户先前拒绝了我的请求并做了一些事情,如果用户拒绝我的请求并检查不要再提问

+1

_“因此,与从来没有被要求在第一次运行权限验证码用户” _'shouldShowRequestPermissionRationale'应该返回'假'如果你的应用程序尚未向用户请求权限,那么'else'子句将在第一次运行时执行。 – Michael

+0

[Android M的可能重复权限:对shouldShowRequestPermissionRationale()函数的使用感到困惑(https://stackoverflow.com/questions/32347532/android-m-permissions-confused-on-the-usage-of-shouldshowrequestpermissionrati) –

+0

@Michael但android.com认为是不同的:如果用户过去关闭了权限请求,并在权限请求系统对话框中选择了“不要再请求”选项,该方法返回false。 –

回答

0

首先检查权限是否被授予然后做你需要的 否则如果权限被拒绝,那么检查天气,你应该通过shouldShowRequestPermissionRationale请求你需要的权限。
如果shouldShowRequestPermissionRationale返回false,那么您可以向用户显示一条消息,告诉他们手动启用权限。
其他然后如果shouldShowRequestPermissionRationale返回true,那么请求许可并获得onRequestPermissionsResult授予权限

更新的结果,这只是一个简单的代码来显示的步骤:

if (checkSelfPermission == granted){ 
// do what you want 
} else if (shouldShowRequestPermissionRationale == true) { 
     // you can request the permission you want from the user, then check whether permission granted or not inside onRequestPermissionsResult method 
} else { 
     // here you know the permission is not granted , and also the user check on "Dont ask Again!" checkbox, so all you can to do is just tell the user to enable the permission manually from app permissions through Toast message or any thing else 
     } 
+0

首先,我将检查是否未授予权限,所以在这个范围内,我会检查我是否应该ShowShowRequestPermissionRationale,以便告诉用户您第一次拒绝了我的请求,但是我再次请求您。否则我会告诉用户我不能让你允许我的请求,因为你检查了**不要再问**!那么,如何让我的应用程序适用于所有情况? –

+0

@ArtinArtin看到更新的答案 –

+0

你是对的,但在第一次应用程序运行时,另一方面当用户选中时**不要再询问** ** else **部分将执行!你同意吗?其他部分将在两种情况下执行!如果我告诉用户应该在其他部分的设置中启用权限,它也会在第一次运行时出现! –

0
@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     //initilize your views 


    if(iscontactsAllowed){ 

    // do your code here 

    } else { 

    requestcontactsPermission(); 

    } 

} 
private void requestcontactsPermission() { 

     if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_CONTACTS)) { 
      //If the user has denied the permission previously your code will come to this block 
      //Here you can explain why you need this permission 
      //Explain here why you need this permission 
      Log.d("scancode", "denied permission before"); 
     } 

     Log.d("perm", "fourth"); 
     //And finally ask for the permission 
     ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_CONTACTS}, READ_CONTACTS_CODE /*can be any interge */); 

    } 

private boolean iscontactsAllowed() { 
      //Getting the permission status 
      int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS); 

      //If permission is granted returning true 
      if (result == PackageManager.PERMISSION_GRANTED) 

       return true; 

      //If permission is not granted returning false 
      return false; 
     } 


@Override 
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 

     //Checking the request code of our request 

     if(requestCode == READ_CONTACTS_CODE){ 

if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

// you have the permission call yur method here 

} else { 

// permission denied show user why you need it or ask again by calling reuestpermission if you need the permission 
} 

} 
0

@ArtinArtin我已经扩展了@salmanyahya更新简单的代码,并提供了我的逻辑与警报对话框和一个Snackbar(不是Snackbar的大粉丝)任何方式看看是否有帮助

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { 
      //.... write file into storage ... 
      System.out.println("SDK > BuildVersion TRUE"); 
     } else { 
      requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 666); // Comment 26 
      System.out.println("go to requestPermissions"); 
     } 
    } 
    onLoad(); 
} 

@Override 
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 

    super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
    switch (requestCode) { 

     case 666: // Allowed was selected so Permission granted 
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

       Snackbar s = Snackbar.make(findViewById(android.R.id.content),"Permission Granted",Snackbar.LENGTH_LONG); 
       View snackbarView = s.getView(); 
       TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text); 
       textView.setTextColor(Color.RED); 
       textView.setTextSize(18); 
       textView.setMaxLines(6); 
       s.show(); 

       // do your work here 

      } else if (Build.VERSION.SDK_INT >= 23 && !shouldShowRequestPermissionRationale(permissions[0])) { 
       // User selected the Never Ask Again Option Change settings in app settings manually 
       AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); 
       alertDialogBuilder.setTitle("Change Permissions in Settings"); 
       alertDialogBuilder 
         .setMessage("" + 
           "\nClick SETTINGS to Manually Set\n"+"Permissions to use Database Storage") 
         .setCancelable(false) 
         .setPositiveButton("SETTINGS", new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int id) { 
           Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); 
           Uri uri = Uri.fromParts("package", getPackageName(), null); 
           intent.setData(uri); 
           startActivityForResult(intent, 1000);  // Comment 3. 
          } 
         }); 

       AlertDialog alertDialog = alertDialogBuilder.create(); 
       alertDialog.show(); 

      } else { 
        // User selected Deny Dialog to EXIT App ==> OR <== RETRY to have a second chance to Allow Permissions 
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { 

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); 
        alertDialogBuilder.setTitle("Second Chance"); 
        alertDialogBuilder 
          .setMessage("Click RETRY to Set Permissions to Allow\n\n"+"Click EXIT to the Close App") 
          .setCancelable(false) 
          .setPositiveButton("RETRY", new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog, int id) { 
            //ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Integer.parseInt(WRITE_EXTERNAL_STORAGE)); 
            Intent i = new Intent(MainActivity.this,MainActivity.class); 
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
            startActivity(i); 
            } 
          }) 
          .setNegativeButton("EXIT", new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog, int id) { 
            finish(); 
            dialog.cancel(); 
           } 
          }); 
        AlertDialog alertDialog = alertDialogBuilder.create(); 
        alertDialog.show(); 
       } 
      } 
      break; 
    }}; 
0

此密码可帮助处理在Android上运行时的权限管理

public String storagePermissions = Manifest.permission.READ_EXTERNAL_STORAGE; 
private static final int REQUEST_ACCESS =101; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.activity_main); 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     if(checkSelfPermission(storagePermissions)== PackageManager.PERMISSION_GRANTED){ 
      result(); // result is your block of code 
     }else { 
      requestPermissions(new String[]{storagePermissions},REQUEST_ACCESS); 
     } 

    } 
    else{ 
     result(); //so if user is lower than api verison M, no permission is requested 
    } 

} 

private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) { 
    new AlertDialog.Builder(MainActivity.this) 
      .setMessage(message) 
      .setTitle("Hi User..") 
      .setPositiveButton("Ok", okListener) 
      .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) {  //idea calling showMessage funtion again 
        Snackbar mySnackbar = Snackbar.make(findViewById(R.id.coordinatorlayout),"You Press Cancel.. ", Snackbar.LENGTH_INDEFINITE); 
        mySnackbar.setAction("Exit", new cancelButton()); 
        mySnackbar.show(); 

       } 
      }) 
      .create() 
      .show(); 
} 


private void result(){ 
      //your code 
} 

    @RequiresApi(api = Build.VERSION_CODES.M) 
public class NeverAskAgain implements View.OnClickListener{ 
    @Override 
    public void onClick(View view) 
    { 
     goToSettings(); 
    } 
} 
@RequiresApi(api = Build.VERSION_CODES.M) 
private void goToSettings() { 
    Intent myAppSettings = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getPackageName())); 
    finish(); 
    myAppSettings.addCategory(Intent.CATEGORY_DEFAULT); 
    myAppSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    startActivityForResult(myAppSettings, REQUEST_APP_SETTINGS); 
} 
public class cancelButton implements View.OnClickListener{ 
    @Override 
    public void onClick(View view){ 
     Toast.makeText(MainActivity.this,"To use this app , you must grant storage permission",Toast.LENGTH_SHORT); 
     finish(); 
    } 
    } 


@Override 
@RequiresApi(api = Build.VERSION_CODES.M) 
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { 
    super.onRequestPermissionsResult(requestCode,permissions,grantResults); 

    switch(requestCode) { 
     case REQUEST_ACCESS: 
       if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
        // permission is granted 
        result(); 
        break; 
       } 
       else if (!shouldShowRequestPermissionRationale(permissions[0])){ 
        showMessageOKCancel("You choose Never Ask Again,option", 
       new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         Snackbar mySnackbar = Snackbar.make(findViewById(R.id.coordinatorlayout), "Permission=>Storage=>On", Snackbar.LENGTH_INDEFINITE); 
         mySnackbar.setAction("Settings", new NeverAskAgain()); 
         mySnackbar.show(); 
        } 
        }); 
        break; 
       } 
       else { 
        showMessageOKCancel("You Denid permission Request..", 
        new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, int which) { 
          requestPermissions(new String[]{storagePermissions}, REQUEST_ACCESS); 
         } 
        }); 
        break; 
       } 
     } 
}