Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if there is front camera and if there is how to reach and use front camera?

Tags:

android

camera

How to detect if there is a front camera and if there is how to reach and use front camera ?

like image 821
shiz Avatar asked Oct 14 '10 21:10

shiz


3 Answers

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.

like image 177
Oak Avatar answered Oct 21 '22 23:10

Oak


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.

like image 45
Kalpit Champanery Avatar answered Oct 22 '22 01:10

Kalpit Champanery


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!

like image 1
CommonsWare Avatar answered Oct 22 '22 00:10

CommonsWare