2017-05-04 115 views
0

我試圖打開相機,但錯誤關閉了應用程序。昨天的代碼工作,由於某種原因,現在沒有物理的手機上運行CameraManager.openCamera缺少所需權限:android.permission.CAMERA

私人無效connectCamera(){

CameraManager cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE); 
    try { 
     if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { 
      throw new RuntimeException("Time out waiting to lock camera opening."); 
     } 

     int permissionCheck = ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA); 

     if (permissionCheck != PackageManager.PERMISSION_GRANTED) { 

      ActivityCompat.requestPermissions((Activity)context, PERMISSIONS, PERMISSION_ALL); 
      //java.lang.SecurityException: Lacking privileges to access camera service 
     } 

     cameraManager.openCamera("0", mCameraDeviceStateCallback,null); 

    } catch (CameraAccessException e) { 
     e.printStackTrace(); 
    } catch (InterruptedException e) { 
     throw new RuntimeException("Interrupted while trying to lock camera opening.", e); 
    } 
} 

java.lang.SecurityException: Lacking privileges to access camera service

回答

0

的問題是,ActivityCompat.requestPermissions(...)是非阻塞的,所以實際發生的事情是你的應用程序請求允許但在此之前,用戶可以授予它(或者可以顯示甚至對話框),該cameraManager.openCamera(...)線被執行,如果事先沒有授予權限,顯然會引發異常。這意味着你必須在這裏分理處辦理業務:

  • ,如果你有授予權限,執行cameraManager.openCamera(...)
  • 如果具有的權限授予調用ActivityCompat.requestPermissions(...)並等待在onRequestPermissionsResult(...)結果

當你有結果(和許可被允許了),你可以打開攝像頭:

@Override 
public void onRequestPermissionsResult(int requestCode, 
     String permissions[], int[] results) { 
    switch (requestCode) { 
     case PERMISSION_ALL: 
      if (results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED) { 
       // permission granted 
       cameraManager.openCamera("0", mCameraDeviceStateCallback,null); 
      } else { 
       // permission denied 
      } 

      return; 
    } 
} 

也不要忘了把這個權限在你的清單文件太多,如果你minSdkVersion小於23

更多細節退房Requesting Permissions at Run Time