Asus Nexus 7 2013 camera.open Fail to connect to c

2019-08-29 06:58发布

问题:

I have an issue only on Asus Nexus 7 2013. All other devices, including Asus Nexus 7 2012 works fine.
This device has 2 camera IDs: 0, 1.
But I can't open camera, using both of them.

//...
try {
     //cameraID: 0 or 1
     camera = Camera.open(cameraID);
     //...
} catch (Exception e) {
     e.printStackTrace();
}

So I getting:

java.lang.RuntimeException: Fail to connect to camera service
android.hardware.Camera.<init>(Camera.java:495)
android.hardware.Camera.open(Camera.java:341)

回答1:

Problem was in new Android 6+ feature: Request Permission at Runtime.

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
    if (!permissionRequestInProgress) {
          permissionRequestInProgress = true;
              new Handler().post(new Runnable() {
                  @Override
                  public void run() {
                      if (ContextCompat.checkSelfPermission(RootActivity.this, Manifest.permission.CAMERA)
                              != PackageManager.PERMISSION_GRANTED)
                      {
                          ActivityCompat.requestPermissions(RootActivity.this,
                                        new String[]{Manifest.permission.CAMERA},
                                        CAMERA_PERMISSION_REQUEST);
                      } else {
                          //we got it
                      }
              }
           });
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case CAMERA_PERMISSION_REQUEST:
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted
                //we got it
            } else {
                // permission denied
            }
            permissionRequestInProgress = false;
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}