I'm always excited to take on new projects and collaborate with innovative minds.

Address

Court Road, Gujrat, Pakistan

Social Links

Android Development

Using CameraX with Jetpack Compose for Real-Time Device AI on Android

Learn how to use CameraX with Jetpack Compose to build real-time on-device AI apps. Covers fullscreen preview, ImageAnalysis, threading, performance, and ML integration.

Using CameraX with Jetpack Compose for Real-Time AI on Android

Real-time AI apps like face detection, pose tracking, document scanning, and smart cameras depend on one critical foundation: a fast, reliable camera pipeline. On Android, that foundation is CameraX.

In this blog, you’ll learn how to combine CameraX + Jetpack Compose to power real-time on-device AI without UI lag, dropped frames, or broken previews.

This guide is written for Android developers who want to build production-grade AI apps, not just demos.


Why CameraX Is Critical for Device AI

CameraX is Google’s recommended camera library because it solves problems that direct Camera2 usage makes painful:

  • Lifecycle safety
  • Consistent behavior across devices
  • Easy access to real-time frames
  • Composable integration with ML pipelines

For AI apps, CameraX enables:

  • Real-time frame analysis
  • Controlled frame rate (FPS throttling)
  • Separation of UI and inference work
  • Stable previews across Android versions

Core CameraX Use Cases for AI Apps

CameraX is built around use cases. AI apps typically rely on three:

1. Preview

Displays the live camera feed to the user.

2. ImageAnalysis

Provides frames for AI processing (face detection, pose tracking, OCR). This is where ML runs.

3. ImageCapture (Optional)

Used when the app needs to take photos in addition to live analysis.

For most real-time AI apps, Preview + ImageAnalysis is enough.


CameraX + Jetpack Compose Architecture

Jetpack Compose does not replace CameraX. Instead, Compose hosts CameraX using interoperability components.

The recommended pattern is:

  1. CameraX runs in the View layer
  2. AI inference runs in background threads
  3. Compose observes AI results via the state
  4. Compose draws overlays (boxes, landmarks)

This separation is critical to avoid UI freezes.


Setting Up CameraX Dependencies (Gradle KTS)

kotlin dependencies { 
implementation("androidx.camera:camera-camera2:1.3.0") implementation("androidx.camera:camera-lifecycle:1.3.0") implementation("androidx.camera:camera-view:1.3.0") 
}

These libraries give you:

  • Camera2 compatibility
  • Lifecycle-aware camera handling
  • PreviewView for rendering camera feed

Requesting Camera Permission (Required)

CameraX will not work without runtime permission. In Compose, permissions must be handled explicitly.

val permissionState = rememberPermissionState( android.Manifest.permission.CAMERA )
LaunchedEffect(Unit) { permissionState.launchPermissionRequest() }

Always block camera initialization until permission is granted.


Displaying Fullscreen Camera Preview in Compose

A common mistake is seeing the preview only partially rendered. The correct approach is using AndroidView + MATCH_PARENT.

AndroidView(
    modifier = Modifier.fillMaxSize(),
    factory = { context ->
        PreviewView(context).apply {
            scaleType = PreviewView.ScaleType.FILL_CENTER
        }
    }
)

This ensures the camera feed fills the entire screen.


ImageAnalysis for Real-Time AI

This is where AI magic happens.

val analysis = ImageAnalysis.Builder()
    .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
    .build()
analysis.setAnalyzer(Executors.newSingleThreadExecutor()) { imageProxy ->
    // Send imageProxy to ML Kit or MediaPipe for processing
    imageProxy.close() // Make sure to close it to avoid memory leaks
}

KEEP_ONLY_LATEST prevents backlog and UI lag.


Threading: The Golden Rule of AI Apps

Never run AI inference on the main thread.

  • Camera runs on the camera thread
  • ML runs on the background executor
  • Compose UI runs on the main thread

Breaking this rule causes dropped frames, ANRs, and bad UX.


Passing AI Results to Compose UI

AI results should be exposed as a state.

val detectedFaces = mutableStateOf<List<Face>>(emptyList())

Compose automatically redraws overlays when state updates.


Drawing AI Overlays on Camera Feed

Overlays must be drawn using Canvas on top of the preview.

Canvas(modifier = Modifier.fillMaxSize()) {
    detectedFaces.value.forEach { face ->
        drawRect(
            color = Color.Green,
            topLeft = Offset(
                face.boundingBox.left.toFloat(),
                face.boundingBox.top.toFloat()
            ),
            size = Size(
                face.boundingBox.width().toFloat(),
                face.boundingBox.height().toFloat()
            )
        )
    }
}

Coordinate mapping must account for:

  • Preview size vs image size
  • Rotation
  • Mirroring (front camera)

FPS Throttling for Battery & Performance

Running AI on every frame is unnecessary.

Best practice:

  • Limit inference to 10–15 FPS
  • Drop intermediate frames
  • Reuse ML objects

This dramatically improves battery life.


Common CameraX + AI Mistakes

  • Running ML on main thread
  • Not closing ImageProxy
  • Incorrect preview scaling
  • Ignoring device rotation
  • Hardcoding coordinates

Why This Setup Scales to Production

This architecture:

  • Works fully offline
  • Respects user privacy
  • Scales from ML Kit to MediaPipe
  • Is Google Play compliant

This is the same foundation used by real-world AI apps.


Need Help Building a Real-Time AI Camera App?

If you’re building an AI-powered Android app and need help with CameraX, ML integration, or performance optimization, I can help.

View Device AI Services→

Book a Free Consultation →


CameraX Android, CameraX vs Camera2, Android AI Camera, Jetpack Compose Camera, Real-Time AI Android, MediaPipe CameraX, AI App Architecture Android, Android Camera Performance, Device AI Android, ML Camera Android, Android Computer Vision, Offline AI Android
4 min read
Feb 07, 2026
By Syed Ali Raza
Share

Leave a comment

Your email address will not be published. Required fields are marked *

Related posts

Mar 10, 2026 • 8 min read
Android Studio Panda 2 Review: I Used It for the whole week — Here's What Actually Changed

Android Studio Panda 2 ships with a Gemini AI agent that builds apps f...

Mar 02, 2026 • 5 min read
OpenAI Android Integration: Complete 2026 Guide (ChatGPT API + Kotlin Example)

Learn how to implement OpenAI Android integration using Kotlin, Retrof...

Feb 16, 2026 • 7 min read
How to Architect a Scalable Android App in 2026 (MVVM vs MVI Explained)

Learn how to architect a scalable Android app in 2026 using Clean Arch...