Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 4 min read

Wiring Android's MediaPipe LLM Inference API to a Vision-Language Model for Real-Time Screen Understanding

--- title: "Android On-Device VLM Screen Understanding with MediaPipe" published: true description: "Wire MediaPipe's LLM Inference API to a vision-language model on Android for real-time screen understanding β€” token bud

---
title: "Android On-Device VLM Screen Understanding with MediaPipe"
published: true
description: "Wire MediaPipe's LLM Inference API to a vision-language model on Android for real-time screen understanding β€” token budgets, KV-cache, and GPU delegate tradeoffs."
tags: android, kotlin, mobile, architecture
canonical_url: https://mvpfactory.co/blog/android-mediapipe-vlm-screen-understanding
---

## What We Are Building

A real-time screen understanding pipeline on Android using MediaPipe's LLM Inference API and a vision-language model β€” fully on-device. By the end of this walkthrough you will understand the four-stage pipeline, the three failure modes that kill most implementations before they ship, and the tradeoffs that separate a 2-second TTFT from an 8-second one.

## Prerequisites

- Android project targeting API 26+
- MediaPipe 0.10.14
- A compatible on-device VLM (e.g. PaliGemma-3B, INT4 quantized, in MediaPipe format)
- Basic familiarity with `Bitmap` and `MediaProjection`

---

## The Four-Stage Pipeline

The architecture is predictable once you map the stages:

1. **Frame acquisition** β€” `MediaProjection` + `ImageReader` captures the screen as a hardware-backed `Bitmap`
2. **Downsampling** β€” reduce to fit the model's visual token budget
3. **Prompt construction** β€” interleave the downsampled bitmap with the text instruction
4. **Inference** β€” MediaPipe `LlmInferenceSession` streams tokens back asynchronously

Each stage has a failure mode that cascades into the next. Miss one and your latency budget collapses.

---

### Stage 1 & 2: Downsample Before You Encode

`MediaProjection` hands you full-resolution frames β€” typically 1080Γ—2400 on modern Android. That is 2.5 million pixels competing for attention window space. On PaliGemma-3B at INT4 via MediaPipe, a naive full-resolution encode burns 500–800 visual tokens before you write a single word of instruction. On a 1024-token budget that leaves almost nothing for the actual query.

Here is the minimal setup to get this working:


kotlin
fun Bitmap.downsampleForVlm(targetSize: Int = 336): Bitmap {
val scale = targetSize.toFloat() / maxOf(width, height)
val scaledW = (width * scale).toInt()
val scaledH = (height * scale).toInt()
return Bitmap.createScaledBitmap(this, scaledW, scaledH, true)
}


Target 336Γ—336 or 448Γ—448. This keeps visual tokens in the 100–256 range and leaves enough budget for a meaningful text prompt.

---

### Stage 3: Interleave Image Before Text

The ordering matters. Lead with the image, then the instruction β€” this mirrors how the model was fine-tuned:


kotlin
val prompt = LlmInference.InterleaveContent.newBuilder()
.addContent(LlmInference.Content.fromBitmap(downsampled))
.addContent(LlmInference.Content.fromText(
"Describe the interactive elements visible on screen."
))
.build()


Appending the image after the text increases hallucination rates on spatial reasoning tasks. I confirmed this empirically across several open-weight VLMs ported to MediaPipe format.

---

### Stage 4: Gate Your KV-Cache Invalidation

Here is the gotcha that will save you hours. Every time the screen changes, the visual tokens change, and the KV-cache for the image prefix is fully invalidated. You pay full prefill cost on every differing frame. For continuous monitoring that is catastrophic β€” prefilling a 200-token image prefix at 1–2 fps.

Implement perceptual hashing (`dHash`) and only re-prefill when content genuinely changes:


kotlin
fun Bitmap.dHash(): Long {
val small = Bitmap.createScaledBitmap(this, 9, 8, true)
var hash = 0L
for (row in 0 until 8) {
for (col in 0 until 8) {
val left = small.getPixel(col, row) and 0xFF
val right = small.getPixel(col + 1, row) and 0xFF
if (left > right) hash = hash or (1L shl (row * 8 + col))
}
}
small.recycle()
return hash
}

fun hammingDistance(a: Long, b: Long): Int = (a xor b).countOneBits()

// Threshold of 10–15 bits handles animation noise without masking real content changes
val shouldInvalidate = hammingDistance(prevHash, currentHash) > 12


A Hamming distance threshold of 10–15 bits handles animation noise without masking real content changes. On UI-heavy screens this can reduce prefill events by 60–80%.

---

## CPU vs GPU Delegate

| Device tier | Delegate | Approx. TTFT | Thermal impact |
|---|---|---|---|
| Pixel 9 Pro | GPU (Adreno 830) | ~1.8–2.5s | Moderate |
| Pixel 9 Pro | CPU (4-thread) | ~6–8s | Low |
| Mid-range (SD 7s Gen 3) | GPU | ~3.5–5s | High |
| Mid-range (SD 7s Gen 3) | CPU | ~10–14s | Moderate |

*PaliGemma-3B, INT4 via MediaPipe 0.10.14, Android 14. Median TTFT over 20 inference runs per configuration, 336Γ—336 input, 60-second warm session. Pixel 9 Pro on stock firmware; mid-range results on Redmi Note 13 Pro (SD 7s Gen 3).*

GPU delegate is non-negotiable if you are targeting anything resembling real-time. The gap is simply too large. The docs do not mention this, but thermal throttling on sustained inference loops will push GPU performance toward CPU numbers within minutes on mid-range devices.

For long-running background services β€” accessibility assistants that stay resident across extended work sessions, like [HealthyDesk](https://play.google.com/store/apps/details?id=com.healthydesk) which monitors developer desk sessions to trigger break reminders β€” thermal management ends up mattering as much as raw TTFT. Implement inference request coalescing, batch user-initiated queries, and add a 500ms cooldown between consecutive GPU inference calls.

---

## Gotchas

**`createScaledBitmap` with `filter = false`** β€” the aliasing artifacts confuse the image encoder and measurably degrade response quality. Always pass `true`.

**Benchmarking cold TTFT only** β€” GPU delegate numbers look impressive in isolation. Measure sustained performance over 5-minute sessions. That is the number that tells you whether your assistant holds up on real hardware.

**Skipping the token budget audit** β€” exceeding ~256 visual tokens on a constrained budget hurts text response quality more than the image resolution loss. Fix the budget first, everything else second.

---

## Conclusion

Let me show you a pattern I use in every project: profile the three failure modes β€” token budget, KV-cache invalidation, thermal throttling β€” before optimising for raw speed. With a 336Γ—336 downsample, perceptual hash gating, and a GPU delegate with cooldown in place, a usable 2-second TTFT on flagship hardware is achievable.

Address those three problems and what looks like a research project becomes a shippable feature.

---

**Resources:**
- [MediaPipe LLM Inference API β€” Android](https://developers.google.com/mediapipe/solutions/genai/llm_inference/android)
- [PaliGemma on-device guide](https://ai.google.dev/edge/mediapipe/solutions/genai/llm_inference)
πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.