Skip to content

CameraX Preview — Complete Guide

DodaTech Updated 2026-06-24 2 min read

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 correct LifecycleOwner.
  • Always call unbindAll() before rebinding.
  • Use PreviewView for automatic surface management.
  • Handle camera availability — the future may fail on devices without a camera.

Common Mistakes with camera x preview

  1. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  2. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  3. Using return to 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

### Why is my preview black?

Camera permission may not be granted, or bindToLifecycle() was called before the LifecycleOwner is active. Ensure permission is granted and the Activity is in onStart.

### How do I switch between front and back camera?

Change CameraSelector.LENS_FACING_FRONT or BACK. Unbind all use cases, update the selector, and rebind. The camera.cameraInfo provides the current facing.

### Can I use CameraX in Compose?

Yes. Use AndroidView wrapping a PreviewView. Bind the camera to the LocalLifecycleOwner inside the AndroidView factory.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro