2017-09-04 131 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; 
       } 
     } 
}