ML Kit: ready-made on-device ML

ML Kit on-device ML in Android: text recognition, barcode, and GenAI prompt APIs with model download, feature checks, and lifecycle rules in Kotlin. About 25 minutes.

Why it matters

  • ML Kit is the shortest path to shipping on-device ML: text recognition, barcode scanning, face detection, image labeling, and translation are ready-made, no training or model bundling required.
  • The GenAI layer (Gemini Nano via Android AICore) adds summarization, proofreading, rewriting, and image description, but only on supported devices, so you must gate every call behind a feature-status check.
  • Interviewers probe model lifecycle, threading, and fallback strategy: a senior candidate explains why a recognizer must be closed, why heavy work stays off the main thread, and what happens when Gemini Nano is not available.
  • Getting any of these wrong produces ANRs, native-memory leaks, or crashes on low-end devices, which is exactly what on-call dashboards flag.

The simple explanation

  • ML Kit is a restaurant that already has the recipes; you do not cook from scratch.
  • Before ordering a GenAI dish you check whether that branch (device) serves it (feature-status check).
  • The chef (model file) must be prepped and on the line (downloaded) before the first plate goes out.
  • After the shift you clean the station (call close()) or the next shift inherits a mess.
  • Some dishes exist only at certain branches; other branches get a simpler menu (a fallback, such as a cloud call or hiding the feature).

ML Kit ships pre-trained models and wraps them in Android-friendly APIs. The classic modules (for example com.google.mlkit:text-recognition, barcode-scanning, face-detection, image-labeling, translate) return a Google Play services Task<T> you can bridge into coroutines. Each one has a getClient() factory (TextRecognition.getClient(...), BarcodeScanning.getClient()); create the client once and reuse it.

The GenAI layer adds two surfaces: feature APIs (summarization, proofreading, rewriting, image description) and a lower-level Prompt API (com.google.mlkit:genai-prompt). Both run Gemini Nano through Android AICore and are available only on supported devices. Before any call you must (1) check feature status (UNAVAILABLE, DOWNLOADABLE, DOWNLOADING, AVAILABLE), (2) trigger the model download if needed, and (3) handle the case where the device is unsupported. GenAI calls work only while your app is in the foreground (no background execution) and AICore enforces usage quotas per app.

LayerDependencyRuns onFallback
Classic APIscom.google.mlkit:text-recognition etc.On-device, inside your app or Play servicesBroadly available
GenAI feature APIscom.google.mlkit:genai-summarization etc.AICoreMust gate; show a "not available" UI
Prompt APIcom.google.mlkit:genai-promptAICoreSame gating; lower-level control

Key rules: create the client once, never block the main thread waiting for a result, and call close() when the screen or feature is done to release native memory. Many classic APIs come in two flavors: bundled (model inside your app, works at once, bigger app) or unbundled (model downloaded by Google Play services, smaller app, may not be ready on first use). GenAI models are managed by AICore; you only trigger the download. Check the current docs for supported devices; the list changes.

Notes

  • Classic ML Kit modules (text-recognition, barcode-scanning, face-detection, image-labeling, translate) return a Task<T>; bridge to coroutines with suspendCancellableCoroutine or await() from kotlinx-coroutines-play-services.
  • Create a TextRecognizer (or equivalent) once via getClient(); do not recreate it per call.
  • GenAI APIs live in com.google.mlkit:genai-prompt and feature modules (summarization, proofreading, rewriting, image description). They run Gemini Nano through Android AICore on supported devices only.
  • Before any GenAI call, check feature status. DOWNLOADABLE means call download(); UNAVAILABLE means show a fallback UI; never crash.
  • GenAI works only while your app is in the foreground and AICore enforces usage quotas. Do not run GenAI inference from a WorkManager job or a background service.
  • Always call close() on recognizers, detectors, and classifiers in onDestroy (or equivalent) to free native memory. Forgetting this leaks the model in native heap.
  • process() already does the work on a background thread and calls your listeners on the main thread. Do not block the main thread with Tasks.await(), and decode or scale big bitmaps off the main thread.
  • The first call can be slower while the model loads. The Prompt API has an optional warmup(); for classic APIs, create the client early if first-call latency matters.
  • Choose bundled vs unbundled per API: bundled works offline on first launch but grows the app; unbundled keeps the app small but the model may still be downloading.
  • Never put an API key in app code or BuildConfig. If a server-side key is needed, keep it on the server and call from there.

Code example

This shows a production-style wrapper around ML Kit TextRecognizer that bridges the Task-based API into a suspend function and exposes a close() for lifecycle cleanup.

import android.graphics.Bitmap
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.text.TextRecognition
import com.google.mlkit.vision.text.TextRecognizer
import com.google.mlkit.vision.text.Text
import com.google.mlkit.vision.text.latin.TextRecognizerOptions
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
 
// One instance per process; inject via Hilt or a ViewModel factory
class OcrHelper {
 
    // Reuse this client; do not create a new recognizer per call
    private val recognizer: TextRecognizer =
        TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS)
 
    // process() runs on ML Kit's own threads; we just suspend until it finishes
    suspend fun recognize(bitmap: Bitmap): String {
        val image = InputImage.fromBitmap(bitmap, 0) // 0 = rotation in degrees
        val text: Text = suspendCancellableCoroutine { cont ->
            recognizer.process(image)
                .addOnSuccessListener { cont.resume(it) }
                .addOnFailureListener { cont.resumeWithException(it) }
        }
        return text.text // full extracted string
    }
 
    // Call in onDestroy or when the feature screen is dismissed
    fun close() = recognizer.close()
}
  • TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS) is called once; the recognizer holds native resources and is not free to create.
  • process() already runs on a background thread, so the caller never blocks the main thread. The suspend function just waits for the result.
  • suspendCancellableCoroutine bridges the Task callbacks into a coroutine. You can also add kotlinx-coroutines-play-services and call await().
  • close() releases native resources. Forgetting it leaks memory and can get the app killed after many screen navigations.

For GenAI, every call starts with a status check. This is the Prompt API flow from the ML Kit docs:

import com.google.mlkit.genai.common.DownloadStatus
import com.google.mlkit.genai.common.FeatureStatus
import com.google.mlkit.genai.prompt.Generation
 
val model = Generation.getClient()
 
suspend fun askNano(prompt: String): String? {
    when (model.checkStatus()) {
        FeatureStatus.UNAVAILABLE -> return null // show fallback UI
        FeatureStatus.DOWNLOADABLE -> model.download().collect { status ->
            if (status is DownloadStatus.DownloadFailed) throw status.e
        }
        FeatureStatus.DOWNLOADING -> return null // ask the user to try again soon
        FeatureStatus.AVAILABLE -> Unit
    }
    // Call only while the app is in the foreground
    return model.generateContent(prompt).candidates.first().text
}

Run the idea in plain Kotlin

interface OnDeviceModel {
  fun isReady(): Boolean
  fun run(input: String): String
  fun close()
}

class SimulatedOcr : OnDeviceModel {
  private var downloaded = false
  private var closed = false

  fun download() {
      downloaded = true
  }

  override fun isReady(): Boolean = downloaded && !closed

  override fun run(input: String): String {
      if (!isReady()) throw IllegalStateException("Model not ready or closed")
      return "recognized: " + input
  }

  override fun close() {
      closed = true
      downloaded = false
  }
}

fun main() {
  val model = SimulatedOcr()
  println("Before download, isReady: " + model.isReady())
  model.download()
  println("After download, isReady: " + model.isReady())
  println("Result: " + model.run("hello world"))
  model.close()
  println("After close, isReady: " + model.isReady())
  try {
      model.run("again")
  } catch (e: IllegalStateException) {
      println("Caught after close: " + e.message)
  }
  println("Lifecycle pattern: check -> download -> run -> close")
}

In production

ANR spike after adding in-app OCR
  • Crashlytics showed a spike in ANRs on a document-scanning screen after adding ML Kit text recognition.
  • The screen decoded full-size camera images on the main thread and then blocked it with Tasks.await() on the process() task.
  • Low-end devices stalled for several seconds on the first inference.
The fix
  • Replaced Tasks.await() with a suspend wrapper and moved bitmap decoding and scaling to Dispatchers.Default.
  • Created the TextRecognizer once in a @Singleton Hilt module instead of per-screen.
  • ANRs from this screen stopped in the next release.
Native OOM after 10 screen navigations
  • Users on a multi-page form app reported the app being killed after navigating through several pages that each used a FaceDetector.
  • Each screen created its own FaceDetector in onCreate but never called close() in onDestroy.
  • Native heap grew significantly per screen; the OS killed the process when it exceeded the limit.
The fix
  • Reproduced by navigating screens in a loop and watching native heap with adb shell dumpsys meminfo.
  • Moved the detector to a shared ViewModel scoped to the activity and called close() in onCleared().
  • Added a lint check that flags any FaceDetector / TextRecognizer / BarcodeScanner without a matching close() call.

Common mistakes

  • Creating a new recognizer per call. Each getClient() loads the model into native memory. Recreating it per call multiplies memory use and adds load time. Create one client per process and reuse it.
  • Blocking the main thread on ML Kit work. Calling Tasks.await() or decoding large bitmaps on the main thread causes ANRs on low-end devices. Suspend on the result instead and keep image prep on a background dispatcher.
  • Calling a GenAI feature without a feature-status check. On unsupported devices the call fails. You must check availability first and show a fallback UI; never assume Gemini Nano is present.
  • Picking bundled or unbundled without thinking. Bundled models grow your app; unbundled models may not be downloaded yet on first use. Choose per feature and handle the not-ready case.
  • Forgetting close() on recognizers and detectors. The model stays in native heap. After several screen navigations the process exceeds the native limit and the OS kills it. Call close() in onDestroy or onCleared().
  • Scheduling GenAI work in a background service or WorkManager. GenAI inference is not supported in the background, and AICore enforces quotas. Background calls fail. Run GenAI only while the app is in the foreground.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How does ML Kit manage the model lifecycle on Android?”

“What are the constraints of ML Kit GenAI APIs compared to classic vision APIs?”

“How do you handle a device that does not support AICore or the NPU?”

“Why must you call close() on ML Kit recognizers, and what happens if you do not?”

Quiz

Which is a correct way to bridge ML Kit's Task-based API into Kotlin coroutines?

What must you do before calling a ML Kit GenAI feature API like summarization?

A user reports the app is killed after navigating through 10 pages that each use a FaceDetector. What is the most likely cause?

Which statement about ML Kit GenAI APIs is correct?

0 of 4 answered

Mini task

Add text recognition to a screenshot viewer (15 min)

  1. Add the bundled Latin text recognition library com.google.mlkit:text-recognition to the app module's build.gradle, using the latest stable version from the ML Kit docs.
  2. Create an OcrHelper class (copy the code from this lesson) that wraps TextRecognizer with a suspend recognize(bitmap: Bitmap): String method and a close() method.
  3. In your screenshot-viewer Activity (or Composable), inject OcrHelper via a ViewModel or a Hilt @Singleton. Call recognize() from a LaunchedEffect or a button click, showing the result in a Text composable or a TextView.
  4. Call ocrHelper.close() in onDestroy() (or onCleared() of the ViewModel).
  5. Open the app on a real device (or an emulator with a camera image), take a screenshot of a text-heavy image, and verify the extracted text appears within 2 seconds.
  6. Navigate away and back three times. Run adb shell dumpsys meminfo <package> before and after. Confirm native heap does not grow by more than a few MB between navigations.

Done condition: Text is extracted and displayed on a real device, close() is called on navigation, and native heap is stable across three navigations.

Next: MediaPipe Tasks: vision, text and audio