QR codes and barcodes are widely used in modern Android applications.
From digital payments and product identification to inventory management, event tickets, and document tracking, barcode scanning has become an essential mobile feature.
Developers can build these capabilities using Google ML Kit Barcode Scanning, CameraX, Kotlin, and Jetpack Compose.
CameraX provides a reliable camera preview and image-analysis pipeline, while ML Kit recognizes barcodes from individual camera frames.
In this tutorial, we’ll build a real-time barcode scanner that supports QR codes and common one-dimensional and two-dimensional barcode formats.
We’ll cover camera permissions, image analysis, barcode detection, Compose UI, scanning overlays, duplicate-result prevention, resource management, security, and performance optimization.
By the end, you’ll understand how to create a practical scanner suitable for production Android applications.
1. What Is Google ML Kit Barcode Scanning?
Google ML Kit is a collection of machine learning APIs designed for mobile applications.
Its Barcode Scanning API can detect and decode supported barcodes from images.
It supports formats such as:
- QR Code
- EAN-13
- EAN-8
- UPC-A
- UPC-E
- Code 128
- Code 39
- Code 93
- ITF
- PDF417
- Data Matrix
- Aztec
- Codabar
Barcode scanning runs on the device.
A backend service is not required simply to recognize a barcode.
However, certain applications may need a backend to validate scanned tickets, retrieve product details, or process business transactions.
2. How Real-Time Barcode Scanning Works
The scanner continuously receives camera frames and sends them to ML Kit for analysis.
Camera Hardware
|
v
CameraX Preview
|
v
CameraX ImageAnalysis
|
v
ImageProxy
|
v
ML Kit Barcode Scanner
|
v
Detected Barcode
|
v
Decoded Value
|
v
Jetpack Compose UI
The preview remains visible while barcode recognition happens asynchronously.
Main components
| Component | Responsibility |
|---|---|
| CameraX Preview | Displays live camera feed |
| ImageAnalysis | Provides camera frames |
| ImageProxy | Represents an individual frame |
| ML Kit BarcodeScanner | Recognizes barcodes |
| ViewModel | Manages scanner UI state |
| Jetpack Compose | Displays scanner controls and results |
3. ML Kit vs ZXing vs Google Code Scanner
Android developers have several barcode scanning options.
| Technology | Best suited for |
|---|---|
| ML Kit Barcode Scanning | Custom real-time camera scanning |
| Google Code Scanner | Simple scanning without building a custom camera UI |
| ZXing | Custom barcode workflows and open-source integrations |
| CameraX + ML Kit | Full control over preview, overlays, and scanning experience |
Which should you choose?
Use Google Code Scanner if your application only needs to launch a standard scanning interface and receive a result.
Use CameraX with ML Kit when you need a branded scanning screen, custom controls, scanning overlays, or integration with other camera features.
This tutorial uses CameraX and ML Kit.
4. Create the Android Project
Create an Android Studio project with:
- Language: Kotlin
- UI toolkit: Jetpack Compose
- Architecture: MVVM
- Minimum SDK: API 23 or higher
- Target SDK: Current Play Store-supported target
The minimum SDK here is a project choice that simplifies compatibility with the bundled ML Kit barcode scanning API.
5. Add Required Dependencies
Open your application-level build.gradle.kts.
dependencies {
// CameraX
implementation(
"androidx.camera:camera-core:<stable-version>"
)
implementation(
"androidx.camera:camera-camera2:<stable-version>"
)
implementation(
"androidx.camera:camera-lifecycle:<stable-version>"
)
implementation(
"androidx.camera:camera-view:<stable-version>"
)
// ML Kit bundled barcode scanner
implementation(
"com.google.mlkit:barcode-scanning:<stable-version>"
)
// Compose and lifecycle
implementation(
"androidx.activity:activity-compose:<stable-version>"
)
implementation(
"androidx.lifecycle:lifecycle-runtime-compose:<stable-version>"
)
implementation(
"androidx.lifecycle:lifecycle-viewmodel-compose:<stable-version>"
)
}
Replace placeholders with compatible stable releases from the official AndroidX and ML Kit documentation.
Bundled vs Google Play services model
ML Kit provides two distribution options.
Bundled model: The barcode recognition model is packaged with your application, increasing application size but making the model available immediately.
Google Play services model: The recognition model can be delivered separately, reducing application package size but potentially requiring a model download.
For a scanner that must work immediately after installation without network connectivity, the bundled model is a practical choice.
6. Configure AndroidManifest.xml
Declare the camera permission:
<uses-permission
android:name="android.permission.CAMERA" />
Declare camera hardware if appropriate:
<uses-feature
android:name="android.hardware.camera.any"
android:required="false" />
Set android:required="true" if camera hardware is essential and you want Google Play to filter incompatible devices.
Does barcode scanning require storage permission?
No.
A real-time CameraX barcode scanner does not require broad photo or storage permissions.
The camera permission is sufficient for acquiring live camera frames.
7. Request Camera Permission in Jetpack Compose
Use the Activity Result API to request camera access.
@Composable
fun ScannerPermissionGate(
content: @Composable () -> 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
}
if (hasPermission) {
content()
} else {
Column {
Text("Camera access is required to scan codes.")
Button(
onClick = {
launcher.launch(
Manifest.permission.CAMERA
)
}
) {
Text("Allow Camera")
}
}
}
}
Best practices
Explain why the permission is needed.
Avoid repeatedly requesting permission after denial.
Provide a route to application settings when permission has been permanently denied.
Recheck permission when the application resumes, because users can change permissions outside the app.
8. Configure ML Kit Barcode Scanner
ML Kit allows developers to restrict recognition to specific barcode formats.
For example, a QR code-only application can request QR detection.
val options =
BarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_QR_CODE
)
.build()
val scanner =
BarcodeScanning.getClient(options)
Support multiple barcode formats
val options =
BarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_QR_CODE,
Barcode.FORMAT_EAN_13,
Barcode.FORMAT_CODE_128,
Barcode.FORMAT_PDF417
)
.build()
Support all recognized formats
val options =
BarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_ALL_FORMATS
)
.build()
Performance recommendation
Enable only the barcode formats your application actually needs.
Restricting formats can improve detection efficiency.
9. Understand CameraX ImageAnalysis
CameraX ImageAnalysis supplies frames from the camera for processing.
Each frame is represented by an ImageProxy.
An analyzer receives these frames:
imageAnalysis.setAnalyzer(
executor,
analyzer
)
The analyzer is responsible for processing each frame and eventually closing its ImageProxy.
Important rule
Every ImageProxy must be closed.
Failing to close frames can stop new frames from reaching the analyzer.
10. Create a BarcodeAnalyzer
Let’s implement an analyzer that processes frames with ML Kit.
class BarcodeAnalyzer(
private val onBarcodeDetected: (String) -> Unit,
private val onError: (Exception) -> Unit
) : ImageAnalysis.Analyzer, AutoCloseable {
private val scanner =
BarcodeScanning.getClient(
BarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_QR_CODE,
Barcode.FORMAT_EAN_13,
Barcode.FORMAT_CODE_128
)
.build()
)
private val busy = AtomicBoolean(false)
override fun analyze(imageProxy: ImageProxy) {
if (!busy.compareAndSet(false, true)) {
imageProxy.close()
return
}
val mediaImage = imageProxy.image
if (mediaImage == null) {
busy.set(false)
imageProxy.close()
return
}
val image = InputImage.fromMediaImage(
mediaImage,
imageProxy.imageInfo.rotationDegrees
)
scanner.process(image)
.addOnSuccessListener { barcodes ->
val value =
barcodes.firstNotNullOfOrNull {
it.rawValue
}
if (value != null) {
onBarcodeDetected(value)
}
}
.addOnFailureListener { error ->
onError(error)
}
.addOnCompleteListener {
busy.set(false)
imageProxy.close()
}
}
override fun close() {
scanner.close()
}
}
How it works
- CameraX delivers an ImageProxy.
- The analyzer converts it to an ML Kit InputImage.
- ML Kit detects supported barcodes.
- The callback receives a decoded value.
- The ImageProxy is closed after processing completes.
Why use AtomicBoolean?
It prevents overlapping ML Kit processing requests.
This reduces unnecessary work when frames arrive faster than they can be analyzed.
Important production consideration
Close the analyzer only after outstanding ML Kit processing has completed, or coordinate shutdown so that pending tasks and ImageProxy instances are safely released.
A production implementation should also guard against publishing results after the camera screen has been disposed.
11. Configure ImageAnalysis Backpressure
CameraX provides backpressure strategies for controlling frame delivery.
For barcode scanning, STRATEGY_KEEP_ONLY_LATEST is usually appropriate.
val imageAnalysis =
ImageAnalysis.Builder()
.setBackpressureStrategy(
ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST
)
.build()
Why use this strategy?
Suppose the camera produces 30 frames per second, but ML Kit processes fewer frames.
Without appropriate backpressure, frames can accumulate and increase latency.
Keeping only the latest available frame helps maintain responsiveness.
Alternative
STRATEGY_BLOCK_PRODUCER can be useful for specialized workloads requiring ordered processing, but may affect preview smoothness.
For typical real-time scanning, prefer keeping only the latest frame.
12. Create the CameraX Scanner Preview
Use PreviewView inside Compose.
@Composable
fun BarcodeCameraPreview(
modifier: Modifier = Modifier,
onBarcodeDetected: (String) -> Unit,
onError: (Exception) -> Unit
) {
val context = LocalContext.current
val lifecycleOwner = LocalLifecycleOwner.current
val previewView = remember {
PreviewView(context)
}
val currentOnDetected by rememberUpdatedState(
onBarcodeDetected
)
val currentOnError by rememberUpdatedState(
onError
)
DisposableEffect(lifecycleOwner) {
val executor =
Executors.newSingleThreadExecutor()
val analyzer = BarcodeAnalyzer(
onBarcodeDetected = {
currentOnDetected(it)
},
onError = {
currentOnError(it)
}
)
val providerFuture =
ProcessCameraProvider.getInstance(context)
var provider: ProcessCameraProvider? = null
var disposed = false
providerFuture.addListener(
{
if (!disposed) {
try {
val cameraProvider =
providerFuture.get()
val preview =
Preview.Builder().build().also {
it.surfaceProvider =
previewView.surfaceProvider
}
val analysis =
ImageAnalysis.Builder()
.setBackpressureStrategy(
ImageAnalysis
.STRATEGY_KEEP_ONLY_LATEST
)
.build()
analysis.setAnalyzer(
executor,
analyzer
)
cameraProvider.bindToLifecycle(
lifecycleOwner,
CameraSelector.DEFAULT_BACK_CAMERA,
preview,
analysis
)
provider = cameraProvider
} catch (error: Exception) {
currentOnError(error)
}
}
},
ContextCompat.getMainExecutor(context)
)
onDispose {
disposed = true
provider?.unbindAll()
// Production cleanup should coordinate
// outstanding ML Kit tasks before closing
// the analyzer and executor.
}
}
AndroidView(
factory = { previewView },
modifier = modifier
)
}
Important implementation note
This illustrates how Preview, ImageAnalysis, and ML Kit fit together.
For production, keep references to the bound use cases and unbind only those owned by the scanner, rather than indiscriminately unbinding unrelated camera sessions.
Implement a deterministic shutdown routine for the analyzer and executor after in-flight processing finishes.
13. Build a Scanner ViewModel
The ViewModel manages scan results and UI state.
data class ScannerUiState(
val scannedValue: String? = null,
val isScanning: Boolean = true,
val errorMessage: String? = null
)
class ScannerViewModel : ViewModel() {
private val _uiState =
MutableStateFlow(ScannerUiState())
val uiState =
_uiState.asStateFlow()
fun onBarcodeDetected(value: String) {
_uiState.update { state ->
if (!state.isScanning) {
state
} else {
state.copy(
scannedValue = value,
isScanning = false
)
}
}
}
fun resetScanner() {
_uiState.value = ScannerUiState()
}
fun onError(message: String) {
_uiState.update {
it.copy(errorMessage = message)
}
}
}
Why separate scanner state?
The camera should not control application navigation or business logic directly.
The analyzer detects barcode data.
The ViewModel decides how the result affects the application.
Compose displays the resulting state.
14. Prevent Duplicate Scan Results
A barcode can appear in dozens of consecutive frames.
Without protection, the same code may trigger repeated actions.
Examples include:
- Opening the same URL multiple times.
- Submitting duplicate inventory updates.
- Navigating repeatedly.
- Triggering multiple network requests.
Recommended solution
Use an explicit scanning state.
fun onBarcodeDetected(value: String) {
_uiState.update { state ->
if (!state.isScanning) {
state
} else {
state.copy(
scannedValue = value,
isScanning = false
)
}
}
}
Once a result is accepted, stop processing further results until the user chooses to scan again.
For high-throughput inventory scanning, use a configurable cooldown or deduplication window instead of permanently pausing after every scan.
15. Create a Jetpack Compose Scanner Screen
@Composable
fun BarcodeScannerScreen(
viewModel: ScannerViewModel = viewModel()
) {
val uiState by viewModel.uiState
.collectAsStateWithLifecycle()
Box(
modifier = Modifier.fillMaxSize()
) {
BarcodeCameraPreview(
modifier = Modifier.fillMaxSize(),
onBarcodeDetected = {
viewModel.onBarcodeDetected(it)
},
onError = {
viewModel.onError(
it.message ?: "Camera error"
)
}
)
ScannerOverlay(
modifier = Modifier.fillMaxSize()
)
Column(
modifier = Modifier
.align(Alignment.BottomCenter)
.navigationBarsPadding()
.padding(24.dp),
horizontalAlignment =
Alignment.CenterHorizontally
) {
if (uiState.scannedValue != null) {
Text(
text = "Scanned Result",
style = MaterialTheme.typography
.titleMedium
)
Text(
text = uiState.scannedValue.orEmpty()
)
Button(
onClick = {
viewModel.resetScanner()
}
) {
Text("Scan Again")
}
} else {
Text(
text = "Place a QR code inside the frame"
)
}
}
}
}
Important note
The overlay is visual guidance.
It does not automatically restrict ML Kit detection to the visible rectangle.
If you need scanning limited to a specific region, implement correct coordinate transformations or image cropping.
16. Create a Scanning Overlay
A scanner interface typically displays a highlighted rectangular area.
@Composable
fun ScannerOverlay(
modifier: Modifier = Modifier
) {
Canvas(modifier = modifier) {
val frameWidth = size.width * 0.75f
val frameHeight = frameWidth
val left = (size.width - frameWidth) / 2f
val top = (size.height - frameHeight) / 2f
drawRoundRect(
color = Color.Green,
topLeft = Offset(left, top),
size = Size(
frameWidth,
frameHeight
),
cornerRadius = CornerRadius(24f),
style = Stroke(width = 6f)
)
}
}
UI recommendations
Use a clear scanning frame.
Keep instructions short.
Avoid excessive animations that distract from scanning.
Ensure the frame remains visible against both light and dark backgrounds.
Consider vibration or sound feedback when a scan succeeds.
17. Add a Scanning Animation
A moving scan line can make the interface feel responsive.
@Composable
fun AnimatedScanLine() {
val transition =
rememberInfiniteTransition(
label = "scanner"
)
val progress by transition.animateFloat(
initialValue = 0f,
targetValue = 1f,
animationSpec = infiniteRepeatable(
animation = tween(
durationMillis = 1800,
easing = LinearEasing
),
repeatMode = RepeatMode.Reverse
),
label = "scanProgress"
)
Canvas(
modifier = Modifier.fillMaxSize()
) {
val y =
size.height * (
0.35f + progress * 0.30f
)
drawLine(
color = Color.Green,
start = Offset(
size.width * 0.15f,
y
),
end = Offset(
size.width * 0.85f,
y
),
strokeWidth = 4f
)
}
}
This is a visual animation, not an actual laser or scanning mechanism.
Barcode recognition still happens through CameraX and ML Kit.
For accessibility, consider reducing or disabling decorative animation when the user requests reduced motion.
18. Detect QR Codes Only
For a dedicated QR code scanner, configure ML Kit with:
val options =
BarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_QR_CODE
)
.build()
QR code use cases
- Website links
- Wi-Fi configuration
- Digital tickets
- Contact details
- App deep links
- Product authentication
- Internal business identifiers
Security reminder
A QR code is simply an encoded data source.
Its contents should not be trusted automatically.
19. Scan Product Barcodes
Retail and inventory applications commonly use EAN and UPC formats.
val options =
BarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_EAN_13,
Barcode.FORMAT_EAN_8,
Barcode.FORMAT_UPC_A,
Barcode.FORMAT_UPC_E
)
.build()
Example workflow
Scan Product Barcode
|
v
Decode Product Identifier
|
v
Query Product Database
|
v
Display Product Details
ML Kit detects the barcode value.
It does not automatically provide product names, prices, inventory, or descriptions.
That information must come from your own database or an appropriate external service.
20. Understand Barcode Result Data
ML Kit returns Barcode objects.
Useful properties include:
rawValuedisplayValueformatvalueTypeboundingBoxcornerPoints
Example
barcodes.forEach { barcode ->
val value = barcode.rawValue
val format = barcode.format
val bounds = barcode.boundingBox
// Process barcode information.
}
rawValue vs displayValue
rawValue represents the decoded content.
displayValue provides a display-oriented representation where available.
For application logic, choose the property appropriate to the specific barcode type and use case.
21. Handle Different QR Code Content Types
ML Kit can classify certain structured barcode contents.
Examples include:
- URLs
- Wi-Fi credentials
- Contact information
- Email addresses
- Phone numbers
- Calendar events
- Geographic coordinates
Example
when (barcode.valueType) {
Barcode.TYPE_URL -> {
val url = barcode.url?.url
}
Barcode.TYPE_WIFI -> {
val wifi = barcode.wifi
}
Barcode.TYPE_CONTACT_INFO -> {
val contact = barcode.contactInfo
}
else -> {
val raw = barcode.rawValue
}
}
Important security consideration
Never automatically open arbitrary URLs or connect to Wi-Fi networks solely because a QR code contains those details.
Display the destination or requested action and obtain user confirmation.
22. Improve Scanning Performance
Real-time image analysis can consume CPU, memory, and battery.
Best practices
Use an appropriate resolution. Higher resolution is not always better. Choose a resolution that provides readable barcodes without unnecessary processing overhead.
Limit barcode formats. Enable only the formats required by your application.
Avoid overlapping processing. Use a busy flag or equivalent mechanism.
Use backpressure. Prefer STRATEGY_KEEP_ONLY_LATEST.
Close ImageProxy. Release every frame when processing completes.
Avoid expensive UI updates. Do not update Compose state for every frame unless necessary.
Stop scanning after success. For one-shot scanning, stop or pause analysis after accepting a result.
Release resources. Close the scanner and shut down executors when the camera session is finished.
23. Add Torch Support
Scanning in low-light environments can be difficult.
CameraX supports torch control on devices with suitable hardware.
if (camera.cameraInfo.hasFlashUnit()) {
camera.cameraControl.enableTorch(true)
}
Disable it with:
camera.cameraControl.enableTorch(false)
Recommended UI
Provide a torch button only when the camera supports it.
Reflect the actual torch state.
Do not assume that every Android device has a rear flash.
24. Add Tap-to-Focus
CameraX supports focus and metering.
val point =
previewView.meteringPointFactory
.createPoint(x, y)
val action =
FocusMeteringAction.Builder(point)
.build()
camera.cameraControl
.startFocusAndMetering(action)
Why focus matters
Small barcodes can be difficult to recognize when the camera is out of focus.
Tap-to-focus helps users scan labels and printed codes at different distances.
For applications scanning very small barcodes, evaluate zoom controls and autofocus behavior on actual hardware.
25. Support Barcode Scanning from Images
Some applications allow users to scan a QR code from an existing image.
You can combine Android Photo Picker with ML Kit.
Example
val image =
InputImage.fromFilePath(
context,
selectedUri
)
val scanner =
BarcodeScanning.getClient()
scanner.process(image)
.addOnSuccessListener { barcodes ->
val values =
barcodes.mapNotNull {
it.rawValue
}
// Display decoded results.
}
.addOnFailureListener {
// Handle decoding failure.
}
Important consideration
The scanner must be closed when no longer needed.
For large image files, consider image dimensions and memory usage.
Use the system Photo Picker rather than broad media permissions for occasional image selection.
26. Security: Never Trust Scanned Data
Barcode content comes from an external source.
A malicious QR code can contain:
- Phishing URLs.
- Misleading deep links.
- Unexpected application commands.
- Extremely long strings.
- Invalid structured data.
- Sensitive information.
Recommended security workflow
Scan Barcode
|
v
Decode Value
|
v
Validate Format
|
v
Check Allowed Action
|
v
Display Confirmation
|
v
Perform User-Approved Action
Important practices
Validate URLs before opening them.
Avoid automatically launching external applications.
Do not execute arbitrary commands from scanned text.
Enforce reasonable length limits.
Use server-side validation for tickets, payments, and inventory operations.
Do not assume a barcode proves authenticity.
27. Barcode Scanning and Privacy
Camera scanning can be implemented entirely on-device.
The ML Kit Barcode Scanning API does not require uploading camera frames to your own server for recognition.
Privacy recommendations
Do not save camera frames unless necessary.
Do not transmit scanned content without a clear purpose.
Avoid logging sensitive QR code contents.
Keep camera access limited to active scanning workflows.
Release camera resources when the scanner is closed.
For business applications, store only the information needed to complete the user’s task.
28. Build a Production Scanner Architecture
A maintainable Android project might use:
com.moiks.barcodescanner/
|
+-- camera/
| +-- BarcodeAnalyzer.kt
| +-- CameraSessionManager.kt
|
+-- domain/
| +-- ScanResult.kt
| +-- BarcodeValidator.kt
|
+-- presentation/
| +-- ScannerViewModel.kt
| +-- ScannerUiState.kt
|
+-- ui/
| +-- ScannerScreen.kt
| +-- ScannerOverlay.kt
| +-- ScannerControls.kt
| +-- ScanResultScreen.kt
|
+-- data/
| +-- ScanHistoryRepository.kt
|
+-- MainActivity.kt
Responsibilities
BarcodeAnalyzer: Converts camera frames and invokes ML Kit.
CameraSessionManager: Manages CameraX binding and cleanup.
BarcodeValidator: Validates decoded content.
ScannerViewModel: Manages scanner state.
ScannerScreen: Displays preview and controls.
ScanHistoryRepository: Optionally stores scan history.
Recommendation
Keep barcode recognition separate from navigation and business actions.
This makes the scanner easier to test and reuse.
29. Test Barcode Scanning
Test on physical devices using real printed and screen-displayed barcodes.
Recommended scenarios
| Scenario | Expected result |
|---|---|
| Valid QR code | Correct content decoded |
| EAN-13 barcode | Correct product identifier |
| Code 128 barcode | Correct value |
| Multiple visible codes | Defined selection behavior |
| Blurry barcode | No crash |
| Low-light environment | Torch improves usability |
| Camera permission denied | Clear permission screen |
| Rapid repeated frames | No duplicate actions |
| Scanner closed during processing | Safe resource cleanup |
| Device rotation | Preview remains correct |
| Background and foreground | Camera resumes appropriately |
| Invalid QR URL | Safe handling |
| Android 13–16 | Consistent functionality |
| Tablet or foldable | Layout remains usable |
Testing recommendation
Use several physical devices with different camera hardware.
A scanner that works on a flagship phone may perform differently on an entry-level device.
30. Common ML Kit Barcode Scanner Mistakes
Mistake 1: Not Closing ImageProxy
This can stall the camera analysis pipeline.
Mistake 2: Processing Every Frame Concurrently
Overlapping recognition requests waste resources.
Mistake 3: Enabling All Barcode Formats Unnecessarily
This can increase recognition workload.
Mistake 4: Updating Compose State for Every Frame
Unnecessary recomposition can affect performance.
Mistake 5: Triggering Duplicate Scan Actions
The same barcode may appear in many frames.
Mistake 6: Ignoring Camera Lifecycle
Camera resources may remain active unnecessarily.
Mistake 7: Assuming Every Device Has Flash
Always check hardware capabilities.
Mistake 8: Automatically Opening QR URLs
Untrusted URLs can create security risks.
Mistake 9: Treating the Visual Overlay as a Detection Boundary
A drawn rectangle does not automatically crop analysis input.
Mistake 10: Testing Only on an Emulator
Physical camera behavior varies significantly.
31. Production Checklist
Before releasing your application:
- Camera permission is handled correctly.
- CameraX Preview is lifecycle-aware.
- ImageAnalysis uses an appropriate backpressure strategy.
- Every ImageProxy is closed.
- ML Kit scanner resources are released.
- Concurrent frame processing is controlled.
- Duplicate scan results are prevented.
- Supported barcode formats are configured.
- Scanner overlay is visible.
- Camera controls respect system insets.
- Torch availability is checked.
- Low-light scanning is tested.
- Invalid barcode content is handled.
- External URLs require safe handling.
- Camera errors are displayed clearly.
- Scanner works across Android versions.
- Physical devices are tested.
- Accessibility is considered.
- User privacy is respected.
32. Frequently Asked Questions
What is the best QR code scanner library for Android?
ML Kit is a strong choice for applications requiring custom real-time barcode scanning with CameraX.
Does ML Kit support QR codes?
Yes. ML Kit supports QR codes and multiple other barcode formats.
Does ML Kit barcode scanning require internet?
The bundled model supports on-device recognition without requiring an internet connection for the scanning operation.
Can ML Kit scan product barcodes?
Yes. It supports common retail barcode formats such as EAN and UPC.
Can CameraX and ML Kit work together?
Yes. CameraX ImageAnalysis provides frames that ML Kit can process.
Does barcode scanning require storage permission?
No. Live camera scanning requires camera access, not broad storage permission.
How do I prevent duplicate scan results?
Use scanning state or a deduplication mechanism to prevent repeated actions.
Can I scan a QR code from a gallery image?
Yes. Use Android Photo Picker to select an image and ML Kit to analyze it.
Can ML Kit scan multiple barcodes in one frame?
Yes. The API can return multiple detected barcodes.
Does ML Kit automatically identify products?
No. It decodes barcode values. Product details require a database or external service.
Can I build an offline QR scanner?
Yes. The bundled ML Kit model supports offline recognition.
Is CameraX required for ML Kit?
No. ML Kit can process supported images from other sources, but CameraX is a convenient choice for real-time scanning.
Is ML Kit suitable for production Android applications?
Yes, when implemented with proper lifecycle handling, resource management, validation, and device testing.
Conclusion
Building a real-time Android QR code and barcode scanner is straightforward with CameraX, ML Kit, Kotlin, and Jetpack Compose.
CameraX provides lifecycle-aware camera access and frame analysis.
ML Kit handles barcode recognition.
Jetpack Compose makes it possible to create modern scanning interfaces with overlays, controls, and responsive feedback.
The most important practices are:
- Use CameraX ImageAnalysis for live camera frames.
- Use ML Kit for barcode recognition.
- Configure only the barcode formats you need.
- Close every ImageProxy.
- Prevent overlapping recognition requests.
- Handle duplicate scan results.
- Manage camera and scanner lifecycles correctly.
- Validate scanned content before taking action.
- Protect user privacy.
- Test across real Android devices.
A reliable barcode scanner is not just about detecting codes quickly. It must also be responsive, secure, lifecycle-aware, and easy for users to operate.
With these techniques, you can implement QR and barcode scanning for inventory management, retail applications, event ticketing, productivity tools, and many other Android products.
Official References
- ML Kit Barcode Scanning
- ML Kit Barcode Scanner API
- Google Code Scanner
- CameraX Overview
- CameraX ImageAnalysis
- CameraX Preview
- Android Camera Permissions
- Jetpack Compose
Published by Moiks Developer Blog — Practical tutorials covering Android, Kotlin, Jetpack Compose, Flutter, React Native, SwiftUI, and modern software engineering.