缺少CameraManager.openCamera所需的权限:android.permission.CAMERA

时间:2017-05-04 01:32:03

标签: android

我试图打开相机,但错误会关闭应用程序。昨天代码工作,由于某种原因现在它在手机上不起作用

private void 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

2 个答案:

答案 0 :(得分:0)

在某些手机上,ActivityCompat.checkSelfPermission不起作用,所以我写了这个,你可以试试。

https://github.com/dengyuhan/CameraPermissionCompat

答案 1 :(得分: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了解详情。