I\'m getting a Fail to connect to camera service exception when I run my Android app in the emulator. I\'ve read the various existing posts but none have fixed this. It is
Isn't an permission on android 6.x?
http://developer.android.com/training/permissions/requesting.html
Using
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(CodeScanner.this, new String[]{android.Manifest.permission.CAMERA}, 50);
}
worked for me
If you periodically got a white screen instead your view of camera - use:
private void releaseCameraAndPreview() {
if (mCamera != null) {
mCamera.setPreviewCallback(null);
mCameraView.getHolder().removeCallback(mCameraView);
mCamera.release();
mCamera = null;
}
}
and put it here
try {
releaseCameraAndPreview();
mCamera = getCameraInstance();
}...
and here
@Override
protected void onPause() {
super.onPause();
releaseCameraAndPreview();
}
From the Android Developers Docs:
Calling Camera.open() throws an exception if the camera is already in use by another application, so we wrap it in a try block.
Try wrapping that code in a try catch block like so:
try {
releaseCameraAndPreview();
if (camId == 0) {
mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
}
else {
mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
}
} catch (Exception e) {
Log.e(getString(R.string.app_name), "failed to open Camera");
e.printStackTrace();
}
Then add this function somewhere:
private void releaseCameraAndPreview() {
myCameraPreview.setCamera(null);
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
OP mentions this in his question, but my issue was I forgot to enable camera emulation in my AVD emulator settings:
If you are using surface View and using code like this`
Observable.create(CameraUtils.getCameraOnSubscribe())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(camera -> {
mCamera = camera.open();
...
}};
Then replace mCamera=camera;