Skip to content Skip to sidebar Skip to footer

Android Camera2 Api Switch Back - Front Cameras

I'm creating a custom camera capturing videos with the new camera2 API. My code is strongly inspired from the code provided by Google here. My camera preview has a button to switch

Solution 1:

What you need to do is introduce new variables:

publicstaticfinalStringCAMERA_FRONT="1";
publicstaticfinalStringCAMERA_BACK="0";

privateStringcameraId= CAMERA_BACK;

remove cameraIdlocal variable from openCamera method.

publicvoidswitchCamera() {
    if (cameraId.equals(CAMERA_FRONT)) {
        cameraId = CAMERA_BACK;
        closeCamera();
        reopenCamera();
        switchCameraButton.setImageResource(R.drawable.ic_camera_front);

    } elseif (cameraId.equals(CAMERA_BACK)) {
        cameraId = CAMERA_FRONT;
        closeCamera();
        reopenCamera();
        switchCameraButton.setImageResource(R.drawable.ic_camera_back);
    }
}

publicvoidreopenCamera() {
    if (mTextureView.isAvailable()) {
        openCamera(mTextureView.getWidth(), mTextureView.getHeight());
    } else {
        mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
    }
}

Solution 2:

After looking at MrOnyszko answer i followed a slightly different approach:

In the Camera2Basic Tutorial a lens facing direction is used to set up the right camera, so i changed this direction before closing and reopening the camera.

privatevoidswitchCamera() {
    if (mCameraLensFacingDirection == CameraCharacteristics.LENS_FACING_BACK) {
        mCameraLensFacingDirection = CameraCharacteristics.LENS_FACING_FRONT;
        closeCamera();
        reopenCamera();

    } elseif (mCameraLensFacingDirection == CameraCharacteristics.LENS_FACING_FRONT) {
        mCameraLensFacingDirection = CameraCharacteristics.LENS_FACING_BACK;
        closeCamera();
        reopenCamera();
    }
}

privatevoidreopenCamera() {
    if (mTextureView.isAvailable()) {
        openCamera(mTextureView.getWidth(), mTextureView.getHeight());
    } else {
        mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
    }
}


privatevoidsetUpCameraOutputs(int width, int height) {
    Activityactivity= getActivity();
    CameraManagermanager= (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        for (String cameraId : manager.getCameraIdList()) {
            CameraCharacteristicscharacteristics= manager.getCameraCharacteristics(cameraId);

            Integerfacing= characteristics.get(CameraCharacteristics.LENS_FACING);
            if (facing != null && facing != mCameraLensFacingDirection) {
                continue;
            }
            ...

Post a Comment for "Android Camera2 Api Switch Back - Front Cameras"