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

Address

Court Road, Gujrat, Pakistan

Social Links

AI Integration

Face Detection on Android Using ML Kit & Jetpack Compose (On-Device AI)

Build a complete on-device face detection Android app using ML Kit, CameraX, and Jetpack Compose. Step-by-step guide with full code, architecture, and best practices.

Face Detection on Android Using ML Kit & Jetpack Compose (Complete App)

On-device AI becomes real when you move beyond theory and build your first working feature. In this guide, you’ll create a complete face detection Android app that runs entirely on the device using ML Kit, CameraX, Kotlin, and Jetpack Compose.

This is not a demo snippet. You’ll build a production-ready face detection app with proper architecture, threading, and UI integration — the same way real apps do it.

No cloud APIs. No image uploads. No privacy risks.
Everything runs locally on the user’s phone.


What You’ll Build in This Blog

  • Real-time face detection using the device camera
  • CameraX + ImageAnalysis pipeline
  • ML Kit face detection (on-device)
  • Jetpack Compose UI with overlay boxes
  • Clean, scalable app structure

Face Detection vs Face Recognition (Important)

Before writing code, understand this clearly:

  • Face Detection → Finds faces (eyes, nose, bounds)
  • Face Recognition → Identifies who the person is

ML Kit only does face detection — which is safer, Play Store–friendly, and perfect for attendance, camera apps, filters, and scanning features.


Project Setup

1. Create Project

  • Android Studio Hedgehog+
  • Minimum SDK: 24+
  • Language: Kotlin
  • UI: Jetpack Compose

2. App-Level File Structure

com.yourapp.facedetection
│
├── MainActivity.kt
│
├── camera/
│   ├── CameraPreview.kt
│   ├── CameraAnalyzer.kt
│   ├── CameraPermissionDenied.kt
│
├── ml/
│   └── FaceDetectorProcessor.kt
│
├── ui/
│   ├── FaceDetectionScreen.kt
│   └── FaceOverlay.kt
│
└── utils/
│   ├── CameraPermissionHandler.kt
    └── cameraPermissionState.kt

This structure keeps camera, ML, and UI logic cleanly separated — essential for real apps.


Gradle Setup (Kotlin DSL)

app/build.gradle.kts

dependencies {

    // CameraX
    implementation("androidx.camera:camera-camera2:1.3.0")
    implementation("androidx.camera:camera-lifecycle:1.3.0")
    implementation("androidx.camera:camera-view:1.3.0")

    // ML Kit (On-device Face Detection)
    implementation("com.google.mlkit:face-detection:16.1.5")

    // Jetpack Compose
    implementation("androidx.activity:activity-compose:1.8.2")
}

Camera Permission

AndroidManifest.xml

<!-- AndroidManifest.xml -->
<uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
<uses-permission android:name="android.permission.CAMERA" />

Setting Up ML Kit Face Detector

FaceDetectorProcessor.kt

import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.face.Face
import com.google.mlkit.vision.face.FaceDetection
import com.google.mlkit.vision.face.FaceDetectorOptions

class FaceDetectorProcessor {

    private val detector = FaceDetection.getClient(
        FaceDetectorOptions.Builder()
            .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_FAST)
            .enableTracking()
            .build()
    )

    fun process(
        image: InputImage,
        onResult: (List<Face>) -> Unit
    ) {
        detector.process(image)
            .addOnSuccessListener { faces ->
                onResult(faces)
            }
            .addOnFailureListener {
                onResult(emptyList())
            }
    }
}

This runs fully on-device with optimized performance.


CameraX Image Analyzer

CameraAnalyzer.kt

import androidx.annotation.OptIn
import androidx.camera.core.ExperimentalGetImage
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.example.facedetection.ml.FaceDetectorProcessor
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.face.Face

class CameraAnalyzer(
    private val processor: FaceDetectorProcessor,
    private val onFacesDetected: (List<Face>) -> Unit
) : ImageAnalysis.Analyzer {

    @OptIn(ExperimentalGetImage::class)
    override fun analyze(imageProxy: ImageProxy) {
        val mediaImage = imageProxy.image ?: return

        val inputImage = InputImage.fromMediaImage(
            mediaImage,
            imageProxy.imageInfo.rotationDegrees
        )

        processor.process(inputImage) { faces ->
            onFacesDetected(faces)
            imageProxy.close()
        }
    }
}

Analysis runs on a background thread, keeping the UI smooth.


Camera Preview with Compose

CameraPreview.kt

import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import androidx.lifecycle.compose.LocalLifecycleOwner
import java.util.concurrent.Executors

@Composable
fun CameraPreview(
    analyzer: ImageAnalysis.Analyzer
) {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current

    AndroidView(
        factory = {
            val previewView = PreviewView(context)

            val cameraProviderFuture =
                ProcessCameraProvider.getInstance(context)

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

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

                val imageAnalysis = ImageAnalysis.Builder()
                    .setBackpressureStrategy(
                        ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST
                    )
                    .build()
                    .also {
                        it.setAnalyzer(
                            Executors.newSingleThreadExecutor(),
                            analyzer
                        )
                    }

                cameraProvider.bindToLifecycle(
                    lifecycleOwner,
                    CameraSelector.DEFAULT_FRONT_CAMERA,
                    preview,
                    imageAnalysis
                )
            }, ContextCompat.getMainExecutor(context))

            previewView
        }
    )
}

Camera Permission Denied UI

CameraPermissionDenied.kt

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color

@Composable
fun CameraPermissionDenied() {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = "Camera permission is required to use face detection",
            color = Color.Red
        )
    }
}

Face Overlay UI

FaceOverlay.kt

import android.graphics.Rect
import android.graphics.RectF
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import com.google.mlkit.vision.face.Face

@Composable
fun FaceOverlay(
    faces: List<Face>
) {
    Canvas(
        modifier = Modifier.fillMaxSize()

    ) {
        faces.forEach { face ->
            val rect = mapRect(
                face.boundingBox,
                size.width,
                size.height,
                size.width,
                size.height
            )

            drawRect(
                color = Color.Green,
                topLeft = Offset(rect.left, rect.top),
                size = Size(rect.width(), rect.height()),
                style = Stroke(width = 4f)
            )
        }
    }
}

fun mapRect(
    boundingBox: Rect,
    imageWidth: Float,
    imageHeight: Float,
    previewWidth: Float,
    previewHeight: Float
): RectF {

    val scaleX = previewWidth / imageWidth
    val scaleY = previewHeight / imageHeight

    return RectF(
        boundingBox.left * scaleX,
        boundingBox.top * scaleY,
        boundingBox.right * scaleX,
        boundingBox.bottom * scaleY
    )
}

Camera Permission and Image Utilities

CameraPermissionHandler.kt


import android.Manifest
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect

@Composable
fun CameraPermissionHandler(
    onPermissionGranted: @Composable () -> Unit,
    onPermissionDenied: @Composable () -> Unit
) {
    val hasPermissionState = cameraPermissionState()

    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission()
    ) { granted ->
        hasPermissionState.value = granted
    }

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

    if (hasPermissionState.value) {
        onPermissionGranted()
    } else {
        onPermissionDenied()
    }
}

cameraPermissionState.kt

import android.Manifest
import android.content.pm.PackageManager
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat

@Composable
fun cameraPermissionState(): MutableState<Boolean> {

    val context = LocalContext.current

    return remember {
        mutableStateOf(
            ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED
        )
    }
}

Main Screen (Everything Connected)

FaceDetectionScreen.kt

import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import com.example.facedetection.camera.CameraAnalyzer
import com.example.facedetection.camera.CameraPermissionDenied
import com.example.facedetection.camera.CameraPreview
import com.example.facedetection.ml.FaceDetectorProcessor
import com.example.facedetection.utils.CameraPermissionHandler
import com.google.mlkit.vision.face.Face

@Composable
fun FaceDetectionScreen() {

    var faces by remember {
        mutableStateOf(emptyList<Face>())
    }

    val processor = remember {
        FaceDetectorProcessor()
    }

    val analyzer = remember {
        CameraAnalyzer(processor) {
            faces = it
        }
    }

    CameraPermissionHandler(
        onPermissionGranted = {
            Box {
                CameraPreview(analyzer)
                FaceOverlay(faces)
            }
        },
        onPermissionDenied = {
            CameraPermissionDenied()
        }
    )
}

MainActivity

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.facedetection.ui.FaceDetectionScreen
import com.example.facedetection.ui.theme.FaceDetectionTheme

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            FaceDetectionScreen()
        }
    }
}

Performance & Best Practices

  • Use FAST performance mode
  • Throttle analysis if needed
  • Never run ML on the UI thread
  • Avoid unnecessary recompositions

Why This App Is Production-Safe

  • Runs fully on-device
  • No biometric storage
  • No network dependency
  • Google Play compliant

Need the complete working code?

👉 Visit the full project repository here:

GitHub Repository: https://github.com/aliraza112/FaceDetectionCompose


Need Help Building an AI-Powered Android App?

I design and build production-ready on-device AI apps using ML Kit, TensorFlow Lite, and Jetpack Compose — optimized for performance, privacy, and Play Store compliance.

Explore Android AI Services→

Book a Free Consultation →

Next up: 👉 CameraX + Jetpack Compose for Real-Time AI Apps (FPS, threading, performance)


Android Face Detection, ML Kit Android, On-device AI Android, Jetpack Compose CameraX, CameraX, Face Detection Kotlin, Face Detection App, Android ML Kit Tutorial, Device AI Android, Android AI, Android AI App
7 min read
Jan 30, 2026
By Syed Ali Raza
Share

Leave a comment

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

Related posts

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 07, 2026 • 4 min read
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-de...

Jan 27, 2026 • 3 min read
How to Set Up Android for Device AI Using Jetpack Compose (Complete Guide)

Learn how to set up Android for on-device AI using Jetpack Compose, ML...