CameraX Preview — Complete Guide
In this tutorial, you'll learn about CameraX Preview. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your CameraX preview shows a black screen, or the preview doesn't stop when the Activity goes to the background.
Wrong Approach ❌
// Binding camera without lifecycle awareness
val cameraProviderFuture = ProcessCameraProvider.getInstance(context)
cameraProviderFuture.addListener(Runnable {
val cameraProvider = cameraProviderFuture.get()
val preview = Preview.Builder().build()
val camera = cameraProvider.bindToLifecycle(
this, CameraSelector.DEFAULT_BACK_CAMERA, preview
)
}, ContextCompat.getMainExecutor(context))
Output: Preview works initially but camera keeps running in background.
Right Approach ✅
class CameraActivity : AppCompatActivity() {
private var cameraProvider: ProcessCameraProvider? = null
private var camera: Camera? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_camera)
val previewView = findViewById<PreviewView>(R.id.previewView)
startCamera(previewView)
}
private fun startCamera(previewView: PreviewView) {
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener({
cameraProvider = cameraProviderFuture.get()
val preview = Preview.Builder()
.build()
.also { it.setSurfaceProvider(previewView.surfaceProvider) }
val cameraSelector = CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build()
try {
// Unbind before rebinding
cameraProvider?.unbindAll()
camera = cameraProvider?.bindToLifecycle(
this, // LifecycleOwner
cameraSelector,
preview
)
} catch (e: Exception) {
Log.e("CameraX", "Camera binding failed", e)
}
}, ContextCompat.getMainExecutor(this))
}
override fun onDestroy() {
super.onDestroy()
cameraProvider?.unbindAll() // Clean up
}
// For custom SurfaceProvider (e.g., in Compose)
@Composable
fun CameraPreview(modifier: Modifier = Modifier) {
val context = LocalContext.current
val lifecycleOwner = LocalLifecycleOwner.current
AndroidView(
factory = { ctx ->
PreviewView(ctx).also { previewView ->
val cameraProviderFuture = ProcessCameraProvider.getInstance(ctx)
cameraProviderFuture.addListener({
val provider = cameraProviderFuture.get()
val preview = Preview.Builder().build().also {
it.setSurfaceProvider(previewView.surfaceProvider)
}
try {
provider.unbindAll()
provider.bindToLifecycle(
lifecycleOwner,
CameraSelector.DEFAULT_BACK_CAMERA,
preview
)
} catch (e: Exception) { }
}, ContextCompat.getMainExecutor(ctx))
}
},
modifier = modifier
)
}
}
Output: Camera preview works correctly with proper lifecycle management.
Prevention
- Bind
bindToLifecycle()with the correctLifecycleOwner. - Always call
unbindAll()before rebinding. - Use
PreviewViewfor automatic surface management. - Handle camera availability — the future may fail on devices without a camera.
Common Mistakes with camera x preview
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro