Android code to scan Qr code using camera in android studio using kotlin

 Android code to scan Qr code using camera in android studio using kotlin

scan Qr code

To scan a QR code in Android Studio using Kotlin, you can use the BarcodeDetector class from the Google Mobile Vision library.



First, add the following dependency to your app's build.gradle file:


implementation 'com.google.android.gms:play-services-vision:20.1.0'

Next, create a BarcodeDetector object and use it to scan a QR code from an image or camera preview:


val surfaceView = findViewById<SurfaceView>(R.id.surface_view)


val barcodeDetector = BarcodeDetector.Builder(context)

    .setBarcodeFormats(Barcode.QR_CODE)

    .build()


val cameraSource = CameraSource.Builder(context, barcodeDetector)

    .setAutoFocusEnabled(true)

    .setRequestedPreviewSize(640, 480)

    .build()


surfaceView.holder.addCallback(object : SurfaceHolder.Callback {

    override fun surfaceCreated(holder: SurfaceHolder?) {

        try {

            cameraSource.start(holder)

        } catch (e: IOException) {

            // Handle camera start error

        }

    }


    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {}


    override fun surfaceDestroyed(holder: SurfaceHolder?) {

        cameraSource.stop()

    }

})


barcodeDetector.setProcessor(object : Detector.Processor<Barcode> {

    override fun release() {}


    override fun receiveDetections(detections: Detector.Detections<Barcode>?) {

        val barcodes = detections?.detectedItems

        if (barcodes?.size() > 0) {

            val barcode = barcodes.valueAt(0)

            val qrCode = barcode.rawValue

            // Use the QR code value

        }

    }

})


In this example, the SurfaceView is used to display the camera preview, and the BarcodeDetector is configured to detect QR codes. The setProcessor method is used to set a callback that is called whenever a QR code is detected, and the qrCode variable contains the value of the QR code.


You can customize the camera settings and QR code detection behavior by using the various methods provided by the CameraSource and BarcodeDetector classes. You can find more information and examples in the documentation for the Google Mobile Vision library.


I hope this help !!

Post a Comment

0 Comments