On-device AI cheat sheet
Key ideas
- Create ML Kit recognizers and MediaPipe tasks once and reuse them; each client holds native resources and is not free to create.
- ML Kit GenAI runs Gemini Nano through Android AICore on supported devices only; call
checkStatus()first and handleUNAVAILABLE,DOWNLOADABLE,DOWNLOADINGandAVAILABLE. - GenAI inference runs only while the app is in the foreground; AICore enforces per-app quotas. Never schedule it in
WorkManageror a background service. - MediaPipe Tasks are built with
createFromOptionsfrom a.tflitemodel set inBaseOptions; LIVE_STREAM needs an increasing millisecond timestamp on every call and a result listener on the options builder. - LiteRT (the new name for TensorFlow Lite) uses
CompiledModelas its modern entry point; theInterpreterplus delegate pattern remains in legacy code. List accelerators in order (NPU, GPU, CPU) so the app degrades gracefully. - Call
close()on recognizers, detectors andCompiledModel(and its buffers) when the feature is done, for example inonDestroyoronCleared; close everyImageProxyin afinallyblock. - 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. - LiteRT-LM with
.litertlmfiles replaces the deprecated MediaPipe LLM Inference API (tasks-genai) for new on-device LLM work. - Run all inference off the main thread;
detect()in IMAGE mode is synchronous and can trigger an ANR if called on the UI thread. - 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 term | Use 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) |
FeatureStatus | Result of checkStatus(): UNAVAILABLE, DOWNLOADABLE, DOWNLOADING or AVAILABLE |
ObjectDetector.createFromOptions() | Build a MediaPipe vision task from a .tflite model file and BaseOptions |
RunningMode.LIVE_STREAM | Continuous 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.CPU | List accelerators in CompiledModel.Options; later entries are automatic fallbacks |
ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST | Discard stale camera frames so slow inference does not back up the pipeline |
BitmapImageBuilder | Convert 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 |
suspendCancellableCoroutine | Bridge 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()orcreateFromOptionson every inference. - Never run inference on the main thread; dispatch to
Dispatchers.Defaultor 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_LATESTwith 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.createfails.
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
detectAsyncthrows, the proxy is never closed and the camera pipeline backs up. Wrap the body intry/finallyand close the proxy in thefinallyblock. - 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, triggerdownload()if needed, and show a fallback UI forUNAVAILABLE. - 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.