Search code examples
androidcamera

How can i stop the camera capturs while a Dialag box is showing


Hi have this code in android, if you see in line with a comment //show a dialog box whe i run the app everything goes fine, i can read a qr code correctly. But when i read a valid QRCode and popups the dialog box the camera continuos reading the qr code so if i let the phone in the same position the qrcode was read many times.

I want to stop the reading of the camera until i pres yes or no in the dialog box.

(i'am new in Android so please help me.!!)

regards

    imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this), new QRCodeImageAnalyzer(new QRCodeFoundListener() {
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onQRCodeFound(String _qrCode) throws InterruptedException {
            qrCode = _qrCode;
            Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            vibrator.vibrate(300);
            alertDialog(qrCode.toString()); **// show a dialag box**
        }

        @Override
        public void qrCodeNotFound() {

        }
    }));
    Camera camera = cameraProvider.bindToLifecycle((LifecycleOwner)this, cameraSelector, imageAnalysis, preview);

Solution

  • Finaly i found the solution.! it's feels so good.!!

    I create a nuew class like this

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void stopCamera(@NonNull ProcessCameraProvider cameraProvider){
        cameraProvider.unbindAll();
    }
    

    And before to show the dialog Alert (because a qr code was found) i call stopCamera() after that when the user press yes or no in the dialog box i call again in both to the class StartCamera();

    this is my startCamera class

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startCamera() {
        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                bindCameraPreview(cameraProvider);
            } catch (ExecutionException | InterruptedException e) {
                Toast.makeText(this, "Error starting camera " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }, ContextCompat.getMainExecutor(this));
    

    Thanks a lot, i hope this helps someone.