Android Camera2 API switch back - front cameras

一世执手 提交于 2019-11-30 13:07:10

What you need to do is introduce new variables:

public static final String CAMERA_FRONT = "1";
public static final String CAMERA_BACK = "0";

private String cameraId = CAMERA_BACK;

remove cameraId local variable from openCamera method.

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

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

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

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.

private void switchCamera() {
    if (mCameraLensFacingDirection == CameraCharacteristics.LENS_FACING_BACK) {
        mCameraLensFacingDirection = CameraCharacteristics.LENS_FACING_FRONT;
        closeCamera();
        reopenCamera();

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

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


private void setUpCameraOutputs(int width, int height) {
    Activity activity = getActivity();
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        for (String cameraId : manager.getCameraIdList()) {
            CameraCharacteristics characteristics
                    = manager.getCameraCharacteristics(cameraId);

            Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
            if (facing != null && facing != mCameraLensFacingDirection) {
                continue;
            }
            ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!