Search code examples
androidandroid-fragmentszxing

How to restart camera efficiently in a fragment - Barcode Scanner


I have two fragments in my app and I am trying to implement a barcode scanner using ZXingScanner library in one of them. The implementation works fine. My question is basically related to bad design.

When the user scans a valid code a dialog box appears saying the code is valid. But when i dismiss the dialog (by pressing OK) the barcode scanner stops. To address this issue i have the following:

buttonConfirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    popupView.dismiss();
                    restartCamera();
                }
            });

public void restartCamera(){
    mScannerView.stopCamera(); //mScannerView = new ZXingScannerView(getActivity());
    mScannerView.startCamera();
}

The problem with this approach is that when i switch the fragments the camera is still running behind. How can i stop the camera when i switch to first fragment and then turn it back on AND address this issue. (I am using ViewPager to implement my fragments)


Solution

  • Ok I finally found the solution. I override my setMenuVisibility method in my camera fragment. If the fragment is visible call restartCamera() method otherwise stop the camera.

    @Override
    public void setMenuVisibility(final boolean visible){
        if (visible){
            if (mScannerView != null) {
                Log.v("FragmentQR", "Visible");
                restartCamera();
            }
        }
        else {
            if (mScannerView != null){
                mScannerView.stopCamera();
                Log.v("FragmentQR","InVisible");
            }
        }