1. Switch camera rear to front & front-rear in Camera2 API
In the previous 2 blogs, I have explained Video Recoding using Camera2 API. Furthermore, In this tutorial, I’ll explain about switch camera front-rear via-versa. As you we have to build a CameraVideoFragment.java utility class.
2. Declare below variable in CameraVideoFragment.java.
/** * 0 forback camera * 1 for front camera * Initlity default camera is front camera */ public static final String CAMERA_FRONT = "1"; public static final String CAMERA_BACK = "0"; private String cameraId = CAMERA_FRONT;
3. Check available cameras
We can fetch all available cameras from Camera Manager instance by calling getCameraIdList.It returns all available via getCameraIdList() (front/rear), then you can find the best camera that you want to use or suits your needs.
You can get CameraCharacteristics by using camera ID. You can manage facing, resolution, and filter also. In variable declare block, we define front and back camera id.
In this tutorial, the front camera is the default camera.
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
As above, private String cameraId = CAMERA_FRONT; we set default camera is
4. Furthermore, we can Switch Camera using below code
public void switchCamera() { if (cameraId.equals(CAMERA_FRONT)) { cameraId = CAMERA_BACK; closeCamera(); reopenCamera(); } else if (cameraId.equals(CAMERA_BACK)) { cameraId = CAMERA_FRONT; closeCamera(); reopenCamera(); } }
After changing cameraId we just close the previous camera and reopen it.
public void reopenCamera() { if (mTextureView.isAvailable()) { openCamera(mTextureView.getWidth(), mTextureView.getHeight()); } else { mTextureView.setSurfaceTextureListener(mSurfaceTextureListener); } }
Finally just call switchCamera() method in child Fragment
Place this code and run the project, now you able to see switch camera in camera2 API.