2016-11-07 81 views
0

我只需要一種方法來獲得使用智能手機相機的權限。 我寫了這段代碼,但沒有出現權限請求對話框。如何授予相機權限?

在OnCreate:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 

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

     if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { 
     } else { 
      ActivityCompat.requestPermissions(this, 
        new String[]{Manifest.permission.CAMERA}, 1); 
     } 
    } 

} 



@Override 
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
    switch (requestCode) { 
     case 1: { 
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

       // my code after granted permission 

      } else { 


      } 
      return; 
     } 
    } 
} 
+0

當您在調試器中逐步瀏覽代碼時,您學到了什麼?你真的調用'requestPermissions()'嗎? – CommonsWare

+0

@CommonsWare不,requestPermissions()不會被調用,因爲「ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.CAMERA)」爲true。 – xRobot

回答

1

requestPermissions()不叫,因爲 「ActivityCompat.shouldShowRequestPermissionRationale(這一點,Manifest.permission.CAMERA)」 成立

第1步:顯示一些基本原理(對話框,快餐欄,在你的用戶界面內的東西,無論什麼)

步驟#2:當用戶點擊該基本UI (例如,OK按鈕),請致電requestPermissions()

或者,如果您不想顯示爲什麼要申請許可的理由,請不要撥打shouldShowRequestPermissionRationale()

+0

以及如果我想在用戶打開應用程序時顯示權限請求,該如何處理? – xRobot

+1

@xRobot:恩,執行你問題中的代碼,並在我的答案中顯示修改。請注意,由於您正在使用'ContextCompat'和'ActvityCompat',因此您不需要版本檢查。 – CommonsWare