Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Camera2BasicFragment - problems modifying to switch front/back cameras

I'm trying to modify the Camera2BasicFragment sample project to support switching between the front and back cameras. I added a switch button overlay on the preview screen, and the following code to handle the click. Also a class variable cameraDirection to remember which camera is currently in use:

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.button_take_photo:
            takePicture();
            break;

        case R.id.button_reverse_camera:
            CameraManager manager = (CameraManager) getActivity().getSystemService(Context.CAMERA_SERVICE);
            try {
                String[] cameraIds = manager.getCameraIdList();
                CameraCharacteristics cameraCharacteristics = manager.getCameraCharacteristics(mCameraId);
                for (String id : cameraIds) {
                    if (! id.equals(mCameraId)) {
                        closeCamera();
                        cameraDirection = cameraDirection == CameraCharacteristics.LENS_FACING_FRONT?CameraCharacteristics.LENS_FACING_BACK:
                                CameraCharacteristics.LENS_FACING_FRONT;
                        mCameraId = id;
                        openCamera(mPreviewSize.getWidth(), mPreviewSize.getHeight());
                    }
                }

            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
            break;

    }
}

The annoying thing is that the first switch of the camera works fine. But subsequent switches don't work. What happens is that the preview fades a little, like something is happening, but it remains on the currently selected camera. After a few more clicks on the switch button, the application crashes, and even more annoying is that there's no stack trace. So I've got no idea what the problem is. I suspect a camera lock isn't being released properly, but that's just a guess.

So I'm hoping that someone has successfully modified this sample to handle camera switching, or can recommend an alternative Camera2 fragment implementation.

like image 600
Andrew Fielden Avatar asked May 14 '26 20:05

Andrew Fielden


1 Answers

The problem is in the method setUpCameraOutputs(int width, int height) , where it sets mCameraId=cameraId;, because as it says in its comments

// We don't use a front facing camera in this sample.

I tried with

if(mCameraId==null){
    mCameraId=cameraId;
}

but it's not enough because it does not set the preview size corrrectly for me.

You could modify the method to setUpCameraOutputs(int width, int height, String cameraId) and do the setup correctly.

like image 125
isma3l Avatar answered May 16 '26 09:05

isma3l



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!