How to stop the intent from opening multiple times after scaning QR code with camerax and image analysis use case?

Viewed 358

I am creating a simple qr scanner using Camerax and google ML Kit. I am opening an intent after the string value is extracted from the QR code. The problem I'm facing is , the intent is opening multiple times. How do I resolve this?

The following is the setup for image analysis.DisplayQR intent will open after receiving string value inside QR code.

val imageAnalysis = ImageAnalysis.Builder()
            .setTargetResolution(Size(640, 480))
            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
            .build()

        imageAnalysis.setAnalyzer(
            ContextCompat.getMainExecutor(this),
            CodeAnalyzer(this, object : CallBackInterface {
                override fun onSuccess(qrString: String?) {
                    imageAnalysis.clearAnalyzer()
                    Toast.makeText(this@ActivityQR,qrString,Toast.LENGTH_SHORT).show()
                    Log.d("rty",qrString.toString())
                 //the following intent is opening multiple times
                    val visitordetails =
                        Intent(this@ActivityQR, DisplayQR::class.java)
                    visitordetails.putExtra("VISITOR_QR", qrString)
                    startActivity(visitordetails)
                }
                override fun onFailed() {
                }
            })
        )
        cameraProvider.bindToLifecycle(this, selectedCamera, imageAnalysis, cameraPreview)

Code for analyzing the image

    class CodeAnalyzer(context: Context, callBackInterface: CallBackInterface):imageAnalysis.Analyzer {                                       
    private val context: Context = context
    private val callback: CallBackInterface = callBackInterface

    @SuppressLint("UnsafeOptInUsageError")
    override fun analyze(image: ImageProxy) {
        var scanner: BarcodeScanner = BarcodeScanning.getClient()

        val scannedIMage = image.image
        if (scannedIMage != null) {
            var scannedInputImage = InputImage.fromMediaImage(
                scannedIMage,
                image.imageInfo.rotationDegrees
            )
            scanner.process(scannedInputImage).addOnSuccessListener { barCodes ->
                for (qrCode in barCodes) {
                    when (qrCode.valueType) {
                        Barcode.TYPE_TEXT -> {
                            val qrString: String? = qrCode.rawValue
                            if (qrString != null) {
                               callback.onSuccess(qrString) //Here I am calling the callback

                            }
                        }

                    }
                }

            }.addOnFailureListener {

            }.addOnCompleteListener {
             image.close()
            }   
            }
        }
}

Edit: Corrected activity name

0 Answers
Related