How to detect if there is a front camera and if there is how to reach and use front camera ?
If you are using API level 9 (Android 2.3) or above, you can do the following to calculate the index of the (first) front-facing camera:
int getFrontCameraId() {
CameraInfo ci = new CameraInfo();
for (int i = 0 ; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_FRONT) return i;
}
return -1; // No front-facing camera found
}
you can then use the index for the Camera.open
method, e.g.:
int index = getFrontCameraId();
if (index == -1) error();
Camera c = Camera.open(index);
To get the relevant camera.
Oak your code will not support sdk above 21 so i have added these lines to make it useable :)
int getFrontCameraId(CameraManager cManager) {
if (Build.VERSION.SDK_INT < 22) {
Camera.CameraInfo ci = new Camera.CameraInfo();
for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, ci);
if (ci.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) return i;
}
} else {
try {
for ( int j = 0;j<cManager.getCameraIdList().length; j++) {
String[] cameraId = cManager.getCameraIdList();
CameraCharacteristics characteristics = cManager.getCameraCharacteristics(cameraId[j]);
int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
if (cOrientation == CameraCharacteristics.LENS_FACING_FRONT)
return j;
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
return -1; // No front-facing camera found
}
I have updated the code of Oak which now supports new camera2 library also.
How to detect if there is a front camera and if there is how to reach and use front camera ?
There is no API for this, at least through Android 2.2. With luck, the upcoming Gingerbread release will add built-in support for front-facing cameras. Sorry!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With