On-device AI cheat sheet

Revise on-device AI on Android: ML Kit GenAI, MediaPipe Tasks, LiteRT CompiledModel, CameraX pipelines, and LiteRT-LM for on-device LLMs.

Key ideas

  1. Create ML Kit recognizers and MediaPipe tasks once and reuse them; each client holds native resources and is not free to create.
  2. ML Kit GenAI runs Gemini Nano through Android AICore on supported devices only; call checkStatus() first and handle UNAVAILABLE, DOWNLOADABLE, DOWNLOADING and AVAILABLE.
  3. GenAI inference runs only while the app is in the foreground; AICore enforces per-app quotas. Never schedule it in WorkManager or a background service.
  4. MediaPipe Tasks are built with createFromOptions from a .tflite model set in BaseOptions; LIVE_STREAM needs an increasing millisecond timestamp on every call and a result listener on the options builder.
  5. LiteRT (the new name for TensorFlow Lite) uses CompiledModel as its modern entry point; the Interpreter plus delegate pattern remains in legacy code. List accelerators in order (NPU, GPU, CPU) so the app degrades gracefully.
  6. Call close() on recognizers, detectors and CompiledModel (and its buffers) when the feature is done, for example in onDestroy or onCleared; close every ImageProxy in a finally block.
  7. Large models must be downloaded after install via Play Asset Delivery, Play for On-device AI, or WorkManager; never bundle them in the base APK.
  8. LiteRT-LM with .litertlm files replaces the deprecated MediaPipe LLM Inference API (tasks-genai) for new on-device LLM work.
  9. Run all inference off the main thread; detect() in IMAGE mode is synchronous and can trigger an ANR if called on the UI thread.
  10. Never put an API key in app code or BuildConfig; if a key is needed, keep it on your server and call from there.

APIs at a glance

API or termUse it for
TextRecognition.getClient()Create a TextRecognizer once; reuse it for every OCR call in the process
Generation.getClient()Entry point for the ML Kit GenAI Prompt API (Gemini Nano via AICore)
FeatureStatusResult of checkStatus(): UNAVAILABLE, DOWNLOADABLE, DOWNLOADING or AVAILABLE
ObjectDetector.createFromOptions()Build a MediaPipe vision task from a .tflite model file and BaseOptions
RunningMode.LIVE_STREAMContinuous camera-frame detection; results arrive on a listener, not returned synchronously
CompiledModel.create()Load a LiteRT model with CompiledModel.Options listing accelerators in order; slow, so run it off the main thread
Accelerator.GPU / Accelerator.CPUList accelerators in CompiledModel.Options; later entries are automatic fallbacks
ImageAnalysis.STRATEGY_KEEP_ONLY_LATESTDiscard stale camera frames so slow inference does not back up the pipeline
BitmapImageBuilderConvert a CameraX ImageProxy bitmap into a MediaPipe image for detection
Engine (LiteRT-LM)Built from EngineConfig with a .litertlm path and a Backend; initialize(), then createConversation() and sendMessageAsync
suspendCancellableCoroutineBridge an ML Kit Task into a suspend function (or use await() from kotlinx-coroutines-play-services)
SystemClock.uptimeMillis()Millisecond timestamp that never goes backwards, for LIVE_STREAM detectAsync calls

Snippets

ML Kit OCR with a coroutine bridge

import android.graphics.Bitmap
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.text.Text
import com.google.mlkit.vision.text.TextRecognition
import com.google.mlkit.vision.text.latin.TextRecognizerOptions
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
 
class OcrHelper {
    // Create once and reuse; do not build a recognizer per call
    private val recognizer =
        TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS)
 
    suspend fun recognize(bitmap: Bitmap): String {
        val image = InputImage.fromBitmap(bitmap, 0)
        val text: Text = suspendCancellableCoroutine { cont ->
            recognizer.process(image)
                .addOnSuccessListener { cont.resume(it) }
                .addOnFailureListener { cont.resumeWithException(it) }
        }
        return text.text
    }
 
    fun close() = recognizer.close() // frees native memory
}

CameraX + MediaPipe LIVE_STREAM (fragment; detector is an ObjectDetector created with RunningMode.LIVE_STREAM and a result listener)

val analysis = ImageAnalysis.Builder()
    .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
    .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888)
    .build()
 
analysis.setAnalyzer(cameraExecutor) { proxy ->
    try {
        val mpImage = BitmapImageBuilder(proxy.toBitmap()).build()
        detector.detectAsync(mpImage, SystemClock.uptimeMillis()) // ms, increasing
    } finally {
        proxy.close() // always return the buffer to the camera
    }
}
// When done: analysis.clearAnalyzer(); detector.close()

GenAI feature-status check before inference

import com.google.mlkit.genai.common.DownloadStatus
import com.google.mlkit.genai.common.FeatureStatus
import com.google.mlkit.genai.prompt.Generation
 
class OnDeviceLlm {
    private val model = Generation.getClient()
 
    suspend fun ensureReady(): Boolean = when (model.checkStatus()) {
        FeatureStatus.AVAILABLE -> true
        FeatureStatus.DOWNLOADABLE -> {
            var ok = false
            model.download().collect { s ->
                if (s is DownloadStatus.DownloadCompleted) ok = true
                if (s is DownloadStatus.DownloadFailed) ok = false
            }
            ok
        }
        else -> false // UNAVAILABLE or still DOWNLOADING
    }
 
    fun close() = model.close()
}

Rules of thumb

  • Create one recognizer or detector and reuse it; never call getClient() or createFromOptions on every inference.
  • Never run inference on the main thread; dispatch to Dispatchers.Default or a dedicated single-thread executor.
  • Always call close() on recognizers, detectors and models when the feature is done; forgetting it leaks native memory.
  • Prefer STRATEGY_KEEP_ONLY_LATEST with LIVE_STREAM so stale frames are discarded instead of queued behind slow analysis.
  • Never bundle large models in the base APK; download them after install via Play Asset Delivery, Play for On-device AI, or WorkManager.
  • Always list a GPU or CPU fallback after NPU; if the only accelerator is unsupported, CompiledModel.create fails.

Gotchas

  • Creating a new recognizer per call. Each client holds native resources and is not free to create, so per-call creation wastes memory and time. Create one client and reuse it.
  • Forgetting ImageProxy.close() on the exception path. If conversion or detectAsync throws, the proxy is never closed and the camera pipeline backs up. Wrap the body in try/finally and close the proxy in the finally block.
  • Using System.currentTimeMillis() for LIVE_STREAM timestamps. Wall-clock time can jump backwards when the system clock is adjusted, breaking the increasing-timestamp rule, and the call fails. Use SystemClock.uptimeMillis(), which is monotonic.
  • Calling a GenAI feature without checking FeatureStatus. On devices without Gemini Nano, or before the model is downloaded, the call fails. Call checkStatus() first, trigger download() if needed, and show a fallback UI for UNAVAILABLE.
  • Scheduling GenAI inference in WorkManager or a background service. AICore does not support background inference and enforces per-app quotas; background calls fail. Run GenAI only while the app is in the foreground.
  • Bundling a multi-gigabyte .litertlm file in the base APK. Play size limits reject the upload and users on metered connections cannot install the app. Download the model after install via Play Asset Delivery, Play for On-device AI, or WorkManager.

Quick interview answers

Why should you create an ML Kit recognizer once and reuse it?

The recognizer holds native resources and is not free to create, so recreating it per call wastes memory and time. Create one client, inject it via Hilt or a ViewModel factory, and call close() in onDestroy or when the feature screen is dismissed.

What must you check before calling a GenAI feature API?

Call checkStatus() on the Generation client and branch on the returned FeatureStatus. If it is DOWNLOADABLE, call download() and wait for DownloadCompleted; if UNAVAILABLE, show a fallback UI instead of crashing. Also run inference only in the foreground.

How do you wire MediaPipe LIVE_STREAM to CameraX without frame backup?

Set ImageAnalysis to STRATEGY_KEEP_ONLY_LATEST and OUTPUT_IMAGE_FORMAT_RGBA_8888, then call detectAsync with a SystemClock.uptimeMillis() timestamp inside a try/finally that closes the ImageProxy. If the detector is still busy it drops the new frame, and the camera discards stale ones, so neither side queues up.

What replaces the deprecated MediaPipe LLM Inference API?

LiteRT-LM with .litertlm model files replaces tasks-genai for new on-device LLM work. You create an Engine from an EngineConfig with a Backend (GPU, NPU, or CPU), call initialize() off the main thread, open a conversation with createConversation(), then use sendMessageAsync to stream output as a Flow of chunks.

Why must you call close() on a CompiledModel and its buffers?

LiteRT holds native memory for model weights and tensor buffers that the garbage collector does not free. Skipping close() leaks native memory across screen navigations and can get the app killed, so close buffers and the model in a release step (for example from onCleared) and set the reference to null.

What is the correct timestamp source for LIVE_STREAM detectAsync calls?

Use SystemClock.uptimeMillis(), which the official docs use, because it never goes backwards and is in milliseconds. System.currentTimeMillis() is wall-clock time and can jump backwards, and a non-increasing timestamp makes the call fail.

Go deeper