2015-09-26 91 views
3

我正在測試Android M Dev Preview上的權限系統。我有一個關於回調函數的問題。活動類有一個新的API:Android M權限回撥

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

我想問爲什麼權限和grantResults參數定義爲數組?我知道可以使用requestPermissions()同時詢問多個權限,但是如果請求代碼用於請求的權限集,是不是隻需要一個整數grantResults(不確定權限參數)就足夠了?

+0

除了什麼答案的狀態,我建議使用此librar y以促進進程https://github.com/kayvannj/PermissionUtil –

回答

2

不,因爲用戶可以獨立授予或拒絕您請求的任何權限。

例如,假設我有:

private static final String[] PERMS_ALL={ 
    CAMERA, 
    WRITE_EXTERNAL_STORAGE 
    }; 

我打電話:

requestPermissions(PERMS_ALL, RESULT_PERMS_ALL); 

CAMERAWRITE_EXTERNAL_STORAGE是在不同的權限組。系統會提示用戶每組,以授予或拒絕該權限。他們提供每個權限的結果,因爲我們請求權限(而不是組)。但是,用戶可以:

  • 同時授予
  • 同時拒絕
  • 補助CAMERA但不WRITE_EXTERNAL_STORAGE
  • 補助WRITE_EXTERNAL_STORAGE但不CAMERA

因此,他們給我們的結果全部名單。

就我個人而言,我不會使用這些結果並致電checkSelfPermission(),以防萬一出現一些離奇的競爭情況,我不會用onRequestPermissionResult()撥打電話,用戶通過設置首先改變他們的想法。

2

工作對我來說

檢查並請求許可

if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 


      if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
        android.Manifest.permission.ACCESS_COARSE_LOCATION)) { 

       // Show an expanation 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(this, 
         new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION }, 
         MY_PERMISSIONS_REQUEST_ACCESS_LOCATION); 

       // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an 
       // app-defined int constant. The callback method gets the 
       // result of the request. 
      } 

      return; 
     } 

回調

@Override 
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 
     super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
     switch (requestCode) { 
      case MY_PERMISSIONS_REQUEST_ACCESS_LOCATION: { 
       // If request is cancelled, the result arrays are empty. 
       if (grantResults.length > 0 
         && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

        // permission was granted, yay! Do the 
        // contacts-related task you need to do. 
        moveToNextActivity(); 

       } else { 

        // permission denied, boo! Disable the 
        // functionality that depends on this permission. 
       } 
       return; 
      } 

      // other 'case' lines to check for other 
      // permissions this app might request 
     } 
    }