How to fix “Fail to connect to camera service” exception in Android emulator

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;
    }
}

Leave a Comment