QR Code Scanner in Android

In this article, we are going to implement Bar Code / QR Code scanner in android application. You can also check out android related articles at HERE.

QR Code is 2 dimension bar code. We can scan QR Code / Bar Code through camera. QR Code may contain some data. We can read it through scanner. QR code can be generated from any QR code generator website.

Mobile Vision API supports different types of barcodes: (1) 1D barcodes: EAN-8, UPC-A, EAN-13, EAN-8, UPC-E, Code-93, Code-128, Code-39, Codabar, ITF (2) 2D barcodes: QR Code, Data Matrix, AZTEC, PDF-417

 

Add required library in your app level build.gradle file

implementation ‘com.google.android.gms:play-services-vision:20.1.3’

 

Add Camera Permission in Manifest File

<uses-permission android:name=”android.permission.CAMERA” />
<uses-feature android:name=”android.hardware.camera” />
<uses-feature android:name=”android.hardware.camera.autofocus” />
 
 

Initialize Bar Code Detector

We can start initialize bar code detector in onResume method. We can detect bar code through receive detection method.

var surfaceView: SurfaceView? = null
var cameraSource: CameraSource? = null
var barcodeDetector: BarcodeDetector? = null
var intentData = “”
var txtBarcodeValue: TextView? = null
var btnScanQRCode: Button? = null
val REQUEST_CAMERA_PERMISSION = 151

barcodeDetector = BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.ALL_FORMATS)
.build()

 
 

Initialize Camera Source for QR Code Scanner in Android

cameraSource = CameraSource.Builder(this, barcodeDetector)
.setRequestedPreviewSize(1920, 1080)
.setAutoFocusEnabled(true)
.build()
 
 

Surface View Callbacks for QR Code Scanner in Android

surfaceView?.holder?.addCallback(object: SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder){
try {
if (ActivityCompat.checkSelfPermission(
this@ScanQRBarCodeActivity,
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
) {
cameraSource?.start(surfaceView!!.holder)
} else {
ActivityCompat.requestPermissions(
this@ScanQRBarCodeActivity,
arrayOf(Manifest.permission.CAMERA),
REQUEST_CAMERA_PERMISSION
)
}
} catch (e: IOException) {
e.printStackTrace()
}
}

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

}

override fun surfaceDestroyed(holder: SurfaceHolder){
cameraSource?.stop()
}

 
 

Detect Bar Code in Android

barcodeDetector?.setProcessor(object: Detector.Processor<Barcode>{
override fun release(){
Toast.makeText(getApplicationContext() , “Barcode scanner has been stopped” , Toast.LENGTH_SHORT).show();
}
override fun receiveDetections(detections: Detector.Detections<Barcode>){
val barcodes: SparseArray<Barcode> = detections.detectedItems
if(barcodes.size() != 0){
txtBarcodeValue?.post(Runnable(){
fun run(){
btnScanQRCode?.setText(“LAUNCH URL”)
intentData = barcodes.valueAt(0).displayValue
txtBarcodeValue?.setText(intentData)
}
})
}
}
})
 
 

Open QR Code Scanner in Android

if (intentData.length > 0) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(intentData)))
}
 
 

Final Code

package com.codingwithdhrumil.qrcodescannersample

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.util.SparseArray
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.google.android.gms.vision.CameraSource
import com.google.android.gms.vision.Detector
import com.google.android.gms.vision.barcode.Barcode
import com.google.android.gms.vision.barcode.BarcodeDetector
import java.io.IOException


class ScanQRBarCodeActivity : Activity() {

    var surfaceView: SurfaceView? = null
    var cameraSource: CameraSource? = null
    var barcodeDetector: BarcodeDetector? = null
    var intentData = ""
    var txtBarcodeValue: TextView? = null
    var btnScanQRCode: Button? = null
    val REQUEST_CAMERA_PERMISSION = 151

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scan_qr_bar_code)
        btnScanQRCode?.setOnClickListener {
            if (intentData.length > 0) {
                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(intentData)))
            }
        }
    }

    private fun initializeDetector(){
        barcodeDetector = BarcodeDetector.Builder(this)
            .setBarcodeFormats(Barcode.ALL_FORMATS)
            .build()

        cameraSource = CameraSource.Builder(this, barcodeDetector)
            .setRequestedPreviewSize(1920, 1080)
            .setAutoFocusEnabled(true) //you should add this feature
            .build()

        surfaceView?.holder?.addCallback(object: SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder){
                try {
                    if (ActivityCompat.checkSelfPermission(
                            this@ScanQRBarCodeActivity,
                            Manifest.permission.CAMERA
                        ) == PackageManager.PERMISSION_GRANTED
                    ) {
                        cameraSource?.start(surfaceView!!.holder)
                    } else {
                        ActivityCompat.requestPermissions(
                            this@ScanQRBarCodeActivity,
                            arrayOf(Manifest.permission.CAMERA),
                            REQUEST_CAMERA_PERMISSION
                        )
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }

            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(){
                    Toast.makeText(getApplicationContext() , "Barcode scanner has been stopped" , Toast.LENGTH_SHORT).show();
                }
            override fun receiveDetections(detections: Detector.Detections<Barcode>){
                    val barcodes: SparseArray<Barcode> = detections.detectedItems
                    if(barcodes.size() != 0){
                        txtBarcodeValue?.post(Runnable(){
                            fun run(){
                                btnScanQRCode?.setText("LAUNCH URL")
                                intentData = barcodes.valueAt(0).displayValue
                                txtBarcodeValue?.setText(intentData)
                            }
                        })
                    }
                }
        })

    }

    override fun onPause(){
        super.onPause()
        cameraSource?.release()
    }

    override fun onResume(){
        super.onResume()
        initializeDetector()
    }

}

 
 

qr code scanner in android

 

One thought on “QR Code Scanner in Android

Leave a Reply