Barcode and QR Code Scanner in Jetpack Compose (ML Kit)

Short answer: the fastest way to scan barcodes and QR codes in a Jetpack Compose app is the Google code scanner API from ML Kit. It opens a ready-made scanner screen, needs no camera permission in your app and returns the scanned value in a callback. If you need a custom camera screen, use CameraX with ML Kit barcode scanning.

This guide shows both approaches with Kotlin code. Use the latest library versions from the official ML Kit and CameraX pages, shown here as placeholders.

Option 1: Google code scanner (easiest)

Add the dependency:

dependencies {
    implementation("com.google.android.gms:play-services-code-scanner:SCANNER_VERSION")
}

Then start a scan from a button:

@Composable
fun CodeScannerScreen() {
    val context = LocalContext.current
    var result by remember { mutableStateOf("Nothing scanned yet") }

    Column(
        modifier = Modifier.fillMaxSize().padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        Button(onClick = {
            val options = GmsBarcodeScannerOptions.Builder()
                .setBarcodeFormats(Barcode.FORMAT_QR_CODE, Barcode.FORMAT_EAN_13)
                .build()
            val scanner = GmsBarcodeScanning.getClient(context, options)

            scanner.startScan()
                .addOnSuccessListener { barcode ->
                    result = barcode.rawValue ?: "Empty result"
                }
                .addOnCanceledListener { result = "Scan cancelled" }
                .addOnFailureListener { e -> result = "Error: " + e.message }
        }) {
            Text("Scan a code")
        }

        Text(result)
    }
}

Imports: com.google.mlkit.vision.barcode.common.Barcode, com.google.mlkit.vision.codescanner.GmsBarcodeScannerOptions and com.google.mlkit.vision.codescanner.GmsBarcodeScanning. The scanner runs through Google Play services, so the device needs them. Leave out setBarcodeFormats to scan every supported format.

Option 2: Custom camera screen with CameraX and ML Kit

Use this when you want your own preview, overlay or scanning rules.

dependencies {
    implementation("androidx.camera:camera-camera2:CAMERAX_VERSION")
    implementation("androidx.camera:camera-lifecycle:CAMERAX_VERSION")
    implementation("androidx.camera:camera-view:CAMERAX_VERSION")
    implementation("com.google.mlkit:barcode-scanning:MLKIT_VERSION")
}

Declare the permission in AndroidManifest.xml:

<uses-permission android:name="android.permission.CAMERA" />

Ask for the camera permission

@Composable
fun ScannerWithPermission(onResult: (String) -> Unit) {
    val context = LocalContext.current
    var hasPermission by remember {
        mutableStateOf(
            ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==
                PackageManager.PERMISSION_GRANTED
        )
    }
    val launcher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { granted -> hasPermission = granted }

    LaunchedEffect(Unit) {
        if (!hasPermission) launcher.launch(Manifest.permission.CAMERA)
    }

    if (hasPermission) {
        CameraScanner(onResult)
    } else {
        Text("Camera permission is needed to scan codes.")
    }
}

The camera preview and analyzer

@OptIn(ExperimentalGetImage::class)
@Composable
fun CameraScanner(onResult: (String) -> Unit) {
    val lifecycleOwner = LocalLifecycleOwner.current
    val scanner = remember {
        BarcodeScanning.getClient(
            BarcodeScannerOptions.Builder()
                .setBarcodeFormats(Barcode.FORMAT_QR_CODE, Barcode.FORMAT_EAN_13)
                .build()
        )
    }
    var handled by remember { mutableStateOf(false) }

    AndroidView(
        modifier = Modifier.fillMaxSize(),
        factory = { ctx ->
            val previewView = PreviewView(ctx)
            val providerFuture = ProcessCameraProvider.getInstance(ctx)

            providerFuture.addListener({
                val cameraProvider = providerFuture.get()

                val preview = Preview.Builder().build().also {
                    it.setSurfaceProvider(previewView.surfaceProvider)
                }

                val analysis = ImageAnalysis.Builder()
                    .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                    .build()

                analysis.setAnalyzer(ContextCompat.getMainExecutor(ctx)) { imageProxy ->
                    val mediaImage = imageProxy.image
                    if (mediaImage != null && !handled) {
                        val image = InputImage.fromMediaImage(
                            mediaImage,
                            imageProxy.imageInfo.rotationDegrees
                        )
                        scanner.process(image)
                            .addOnSuccessListener { barcodes ->
                                val value = barcodes.firstOrNull()?.rawValue
                                if (value != null && !handled) {
                                    handled = true
                                    onResult(value)
                                }
                            }
                            .addOnCompleteListener { imageProxy.close() }
                    } else {
                        imageProxy.close()
                    }
                }

                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(
                    lifecycleOwner,
                    CameraSelector.DEFAULT_BACK_CAMERA,
                    preview,
                    analysis
                )
            }, ContextCompat.getMainExecutor(ctx))

            previewView
        }
    )
}

Notes on this code:

  • The handled flag stops the analyzer reporting the same code many times a second.
  • Always call imageProxy.close(), or the camera stops delivering frames.
  • LocalLifecycleOwner lives in androidx.lifecycle.compose in newer Compose versions and in androidx.compose.ui.platform in older ones.
  • imageProxy.image needs the ExperimentalGetImage opt-in.

Which option should you use?

Code scanner API CameraX + ML Kit
Setup A few lines More code
Camera permission in your app Not needed Required
Custom UI and overlay No Yes
Needs Google Play services Yes Not for the bundled ML Kit model

Common mistakes

  • Not closing the ImageProxy. The preview freezes after a few frames.
  • Handling every detected frame. Debounce or stop after the first result.
  • Forgetting the CAMERA permission in the manifest and at runtime for the CameraX option.
  • Scanning every format. Restrict formats to the ones you need for faster, more accurate results.
  • Testing only on an emulator. Test on a real device with good lighting.

FAQ

How do I scan a QR code in Jetpack Compose?

Use the Google code scanner API for the quickest result, or CameraX with ML Kit for a custom camera screen.

Do I need the camera permission?

Not with the Google code scanner API. With CameraX you must declare and request it.

Which barcode formats are supported?

QR Code, EAN-13, EAN-8, UPC-A, UPC-E, Code 128, Code 39, PDF417, Data Matrix, Aztec and more. Check the ML Kit documentation for the full list.

Can I generate QR codes too?

ML Kit scans codes only. Use a library such as ZXing to generate them.

More: Jetpack Compose tutorials and Android tutorials for beginners.