How to Add QR Code Generation and Scanning in an Android App

Blair Fernandes
4 min readMay 21, 2023
Photo by Markus Winkler on Unsplash

QR codes have become an integral part of our digital world, allowing us to quickly and conveniently access information with a simple scan. In this tutorial, we will explore how to implement QR code generation and scanning functionality in your Android app. Whether you want to create QR codes for sharing information or scan them to retrieve data, this guide will provide you with the knowledge and code snippets to get started.

QR Code Generation

QR code generation involves creating a visual representation of data that can be scanned by devices. To implement QR code generation in your Android app, follow these steps:

  1. Add the QR code generation library to your project: Add the following dependencies to your project’s app-level build.gradle file.
implementation 'com.google.zxing:core:3.4.1'
implementation 'com.journeyapps:zxing-android-embedded:4.2.0'

2. Generate QR code: To generate the QR code I have created the following generateQRCode function which generates QR code bitmap based on the provided data.

private fun generateQRCode(data: String): Bitmap? {
val bitMatrix: BitMatrix = try {
val hints = EnumMap<EncodeHintType, Any>(EncodeHintType::class.java)
hints[EncodeHintType.CHARACTER_SET] = "UTF-8"
MultiFormatWriter().encode(
data,
BarcodeFormat.QR_CODE,
qrCodeWidthPixels,
qrCodeWidthPixels,
hints
)
} catch (e: Exception) {
e.printStackTrace()
return null
}

val qrCodeWidth = bitMatrix.width
val qrCodeHeight = bitMatrix.height
val pixels = IntArray(qrCodeWidth * qrCodeHeight)

for (y in 0 until qrCodeHeight) {
val offset = y * qrCodeWidth
for (x in 0 until qrCodeWidth) {
pixels[offset + x] = if (bitMatrix[x, y]) {
resources.getColor(R.color.secondary, theme) // QR code color
} else {
resources.getColor(R.color.primary, theme) // Background color
}
}
}

val bitmap = Bitmap.createBitmap(qrCodeWidth, qrCodeHeight, Bitmap.Config.RGB_565)
bitmap.setPixels(pixels, 0, qrCodeWidth, 0, 0, qrCodeWidth, qrCodeHeight)

// Customize the QR code bitmap (e.g., add a logo)
val logoBitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
val scaledLogoBitmap =
Bitmap.createScaledBitmap(logoBitmap, qrCodeWidth / 4, qrCodeHeight / 4, false)

return combineBitmaps(bitmap, scaledLogoBitmap)
}

The generateQRCode function first creates a BitMatrix using the MultiFormatWriter().encode method and then sets the color of each pixel in the QR code based on the bit value in the BitMatrix. We can also customize the QR code by changing the colors and adding a logo to the QR code. The function returns the final QR code bitmap which we can then display on the screen in an image view.

QR Code Scanning

Implementing QR code scanning functionality allows users to retrieve data from QR codes using their device’s camera. Follow these steps to implement QR code scanning in your Android app:

  1. Request camera permission in your app’s manifest file: Add the following to your app’s AndroidManifest.xml file to request the camera permission.
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.CAMERA"/>

2. Add a button or trigger to start the scanning process: Trigger the following function based on a user input like a button click.

private fun startQRCodeScanner() {
val integrator = IntentIntegrator(this)
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
integrator.setBeepEnabled(false)
integrator.setOrientationLocked(true)
integrator.initiateScan()
}

The startQRCodeScanner function initiates the QR code scanning process in the app. It uses the IntentIntegrator class from the ZXing library to handle the scanning functionality. It sets the desired barcode formats to QR code, disables the beep sound, locks the orientation to the current screen orientation, and then initiates the scan by launching the scanning activity.

3. Handle the scanning result: Once a QR code is scanned by the scanning activity launched in the previous step, we get the result in the overridden onActivityResult method.

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
val result: IntentResult? = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
if (result != null && result.contents != null) {
val scannedData = result.contents
Toast.makeText(this, "Scanned data: $scannedData", Toast.LENGTH_SHORT).show()
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}

This function handles the result of the QR code scanning activity. It uses the IntentIntegrator.parseActivityResult method to parse the result data and retrieve the scanned QR code contents. If the result and its contents are not null, it means a QR code was successfully scanned. Once you get data you can display it to the user or further process it as per your requirements. If the result or the contents are null, it means no QR code was scanned or there was an error.

I have made a small app to demonstrate the QR code generation and scanning functionality. You can get the full code here.

Conclusion

In this tutorial, you have learned how to implement QR code generation and scanning functionality in your Android app. QR codes can be used in various scenarios, such as sharing contact information, URLs, or product details. Integrating QR code functionality can enhance the user experience and provide a convenient way to exchange data. Experiment with different customization options and explore additional features to make your app stand out. Happy coding!

--

--

Blair Fernandes

I am a passionate programmer 💻, geek 🤓 & an avid gamer🎮