CameraView black on when being used for second time

489 views Asked by At

I am using CameraView library for showing a viewfinder and taking snaps from it. I have two buttons, one for opening the view and another button for closing the view.

Both the buttons click will call the following method with true and false parameters:

public void showCameraLayout(boolean show) {
    cameraLoading.setVisibility(View.GONE);
    cameraClick.setVisibility(View.VISIBLE);
    ivGallery.setVisibility(View.VISIBLE);
    if (show) {
        showKeyboard(false);
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) {
            if (mCameraView != null) {
                mCameraView.addCallback(mCallback);
            }
            ViewGroup.LayoutParams params = cameraLayout.getLayoutParams();
            params.height = messagesView.getWidth() / 2;
            cameraLayout.setLayoutParams(params);
            mCameraView.start();
            safeToTakePicture = true;
        } else if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                Manifest.permission.CAMERA)) {
            ConfirmationDialogFragment
                    .newInstance(R.string.camera_permission_confirmation,
                            new String[]{Manifest.permission.CAMERA},
                            REQUEST_CAMERA_PERMISSION,
                            R.string.camera_permission_not_granted)
                    .show(getActivity().getSupportFragmentManager(), FRAGMENT_DIALOG);
        } else {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA},
                    REQUEST_CAMERA_PERMISSION);
        }

    } else {
        ViewGroup.LayoutParams params = cameraLayout.getLayoutParams();
        params.height = 0;
        cameraLayout.setLayoutParams(params);
        if (mCameraView != null) mCameraView.stop();
    }
}

The problem is that when the cameraLayout is opened for the first time I can see the live camera. But when I close it and open it again, then it shows black screen. Weird thing is, I get a proper image if a snap is taken while black screen is being shown.

2

There are 2 answers

1
Quick learner On

after capturing image you should stop the preview and start it back again.

mCamera.stopPreview();
mCamera.startPreview();

try it!

0
Rivaldy Firmansyah On

try putting this in the onStop() function

if(mCameraView.isOpened()) {
   mCameraView.stop();
   mCameraView.destroy();
}