0

I am creating a camera in android using android.hardware.camera2...

I referred to this link

But, I do not know how to switch front camera and back camera.

Please give a advice!

Kanguru
  • 51
  • 4

1 Answers1

1

First of all get the list of camera Ids from device We can use CameraManager to iterate all the cameras that are available in the system, each with a designated cameraId. Using the cameraId, we can get the properties of the specified camera device. Those properties are represented by class CameraCharacteristics. Things like "is it front or back camera", "output resolutions supported" can be queried there.

  CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
        try {
            return manager.getCameraIdList();
        } catch (CameraAccessException e) {
            return null;
        }

Now if you want to open Front camera

 CameraCharacteristics characteristics
                    = manager.getCameraCharacteristics(cameraId);
                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);


   if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
                //Do your code here (open Camera with Camera ID)
            }

This is another method directly which return directly CameraId .

String getFrontFacingCameraId(CameraManager cManager){
for(final String cameraId : cManager.getCameraIdList()){
    CameraCharacteristics characteristics = cManager.getCameraCharacteristics(cameraId);
    int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
    if(cOrientation == CameraCharacteristics.LENS_FACING_FRONT) return cameraId;
}
return null;
}

For More Information about Camera2 Api you can see Here

Harsh Bhavsar
  • 1,561
  • 4
  • 21
  • 39