On-Device LLMs: Building Responsive Android Features with Gemini Nano and Google AI Edge SDK
Modern Android apps increasingly need AI features that feel instant, private, and resilient offline. Cloud LLMs are great for heavy lifting, but even with streaming, latency and connectivity are real-world constraints. On-device LLMs like Gemini Nano close that gap by keeping inference local: lower latency, no data egress, and graceful offline behavior.
In this post, we’ll build a production-ready, end-to-end “Summarize Note” feature that runs on-device with Gemini Nano via Google’s AI Edge SDK, and automatically falls back to the cloud when on-device isn’t available. We’ll focus on a cohesive feature with modern Android patterns, streaming UI, cancellation, model readiness, and failure handling.
Prerequisites
- Android Studio: Koala (2024.1.1) or newer
- Kotlin: 2.0.x
- Coroutines: 1.8.x
- Min SDK: 26
- Target/Compile SDK: 34 or newer
- Device: Pixel with AICore and Gemini Nano support (e.g., compatible Pixel devices); or Emulator for cloud fallback
- Network: Only needed for the fallback path and for initial model download by the system
Dependencies (Gradle)
- Kotlin coroutines
- implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1"
- Lifecycle
- implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.8.3"
- Compose (optional for the UI)
- implementation platform("androidx.compose:compose-bom:2024.06.00")
- implementation "androidx.compose.ui:ui"
- implementation "androidx.compose.material3:material3"
- Hilt (optional, used below)
- implementation "com.google.dagger:hilt-android:2.51.1"
- kapt "com.google.dagger:hilt-android-compiler:2.51.1"
- Google AI Client (cloud fallback)
- implementation "com.google.ai.client.generativeai:generativeai:0.9.0"
- Google AI Edge SDK (on-device)
- Add the latest AI Edge SDK dependency as specified in the official Google AI Edge SDK documentation for Gemini Nano on Android (AICore). Use the latest stable version available at the time you integrate. This provides the on-device text generation client you’ll wire into the Edge provider shown below.
Important: Version names for AI Edge SDK evolve. Keep them updated from the official docs to ensure compatibility with your Android version and AICore.
What we’re building
We’ll implement an MVVM-based feature that:
- Accepts a long note
- Streams a concise summary into the UI as it’s generated
- Uses Gemini Nano on-device when available
- Falls back to Gemini API in the cloud when Nano is not ready/available
- Supports cancellation and timeouts
- Handles edge cases like huge inputs, missing models, and low-memory
We’ll keep the LLM integration behind a small abstraction so you can test, swap providers, and evolve capabilities without refactoring the app.
Architecture overview
- UI (Compose): Displays text, progress, and tokens as they arrive; provides Cancel/Retry
- ViewModel: Owns UI state, starts/cancels work, debounces input
- Repository: Chooses the best LLM provider (Edge vs Cloud), streams results
- Providers:
- EdgeTextGenerator: On-device via AI Edge SDK (Gemini Nano)
- CloudTextGenerator: Cloud via Gemini API SDK
- Model readiness: EdgeCapabilityChecker verifies on-device availability before use
The domain API
We define a small, streaming-first API that both on-device and cloud providers implement.
data class GenerationParams(
val maxOutputTokens: Int = 256,
val temperature: Float = 0.2f, // deterministic summaries
val systemInstruction: String? = null
)
sealed interface StreamEvent {
data class Token(val text: String) : StreamEvent
data class Complete(val fullText: String) : StreamEvent
data class Error(val throwable: Throwable) : StreamEvent
}
interface TextGenerator {
fun streamSummary(
input: String,
params: GenerationParams = GenerationParams()
): kotlinx.coroutines.flow.Flow<StreamEvent>
}
This API allows us to:
- Stream partial tokens
- Signal completion with the cumulative text
- Handle errors distinctly
- Keep configuration centralized
Provider selection and capability checks
We gate the on-device path safely and transparently.
interface EdgeCapabilityChecker {
suspend fun isOnDeviceReady(): Boolean
suspend fun reasonIfUnavailable(): String? // optional details for analytics/UX
}
Implementation notes:
- Prefer the AI Edge SDK/AICore-provided capabilities check (e.g., model availability, downloaded/versioned) rather than ad-hoc package checks.
- If the model is not ready, either prompt the user to enable the feature or silently use cloud fallback depending on your UX policy.
- If you want proactive model availability, use a background task (WorkManager) to trigger/verify model readiness while on unmetered Wi‑Fi and charging, respecting user settings.
On-device provider (Gemini Nano via AI Edge SDK)
Below is a skeleton that demonstrates how you wire the AI Edge SDK into our TextGenerator interface. Replace the “TODO” calls with the actual AI Edge SDK client construction and streaming calls exactly as described in the SDK docs you’re using.
class EdgeTextGenerator(
private val appContext: android.content.Context
) : TextGenerator {
// Consider reusing a single client/session instance (lifecycle-aware) to amortize model load
// cost and reduce memory thrash. Build it lazily and close when not needed.
private val lock = Any()
@Volatile private var client: /* Edge SDK text generation client type */ Any? = null
private fun ensureClient(): /* client type */ Any {
synchronized(lock) {
val cached = client
if (cached != null) return cached as /* client type */
// TODO: Construct the Edge/Nano text generation client.
// This typically requires:
// - Obtaining an AICore/AI Edge SDK session bound to Gemini Nano
// - Supplying generation configuration
// - Handling model download/readiness if the SDK exposes it here
val created = /* Edge client construction */
client = created
return created
}
}
override fun streamSummary(
input: String,
params: GenerationParams
) = kotlinx.coroutines.flow.callbackFlow<StreamEvent> {
try {
val prompt = buildPromptForSummary(input)
// TODO: Start streaming generation using the Edge SDK.
// Pseudocode:
// val session = ensureClient().startSession(params.toEdgeConfig())
// session.generateStream(prompt).collect { token ->
// trySend(StreamEvent.Token(token))
// }
// trySend(StreamEvent.Complete(collectedText))
// Make sure to respect coroutine cancellation (use isActive checks or the SDK’s cancel APIs)
} catch (t: Throwable) {
trySend(StreamEvent.Error(t))
}
awaitClose {
// TODO: cancel active streaming request if the SDK supports it
}
}
private fun buildPromptForSummary(input: String): String {
// Keep prompts short and deterministic for on-device models
return """
Summarize the following note into 3 concise bullet points.
Focus on key facts and decisions. Avoid filler.
Note:
$input
""".trimIndent()
}
}
Key production considerations for the on-device path:
- Session reuse: Create and reuse a session to avoid repeated warm-up time. Close it when the feature is idle.
- Cancellation: Expose cancellation so swipes/back/rotations don’t keep the model busy.
- Memory: Gemini Nano is lightweight relative to cloud LLMs, but still watch memory. Consider an upper bound on input size; pre-truncate to a token budget and inform the user if needed.
- Threading: The SDK typically is non-blocking, but keep heavy work off the main thread.
- Version pin: If the SDK allows specifying a runtime model version, pin to a tested version and roll forward with QA.
Cloud fallback provider (Gemini API via Google AI Client)
The cloud path uses the official Gemini client and supports streaming. This code is production-grade and known-good.
import com.google.ai.client.generativeai.GenerativeModel
import com.google.ai.client.generativeai.type.generationConfig
import com.google.ai.client.generativeai.type.content
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.isActive
class CloudTextGenerator(
apiKey: String,
modelName: String = "gemini-1.5-flash"
) : TextGenerator {
private val model = GenerativeModel(
modelName = modelName,
apiKey = apiKey
)
override fun streamSummary(
input: String,
params: GenerationParams
): Flow<StreamEvent> = callbackFlow {
val prompt = buildPromptForSummary(input)
val config = generationConfig {
temperature = params.temperature.toDouble()
maxOutputTokens = params.maxOutputTokens
}
val request = content { text(prompt) }
// Streaming
try {
val sb = StringBuilder()
val stream = model.generateContentStream(
request,
generationConfig = config
)
// Collect chunks; the SDK provides a Flow-like stream
val job = kotlinx.coroutines.GlobalScope.launch {
try {
stream.collect { chunk ->
if (!isActive) return@collect
val delta = chunk.text.orEmpty()
if (delta.isNotEmpty()) {
sb.append(delta)
trySend(StreamEvent.Token(delta))
}
}
trySend(StreamEvent.Complete(sb.toString()))
} catch (t: Throwable) {
trySend(StreamEvent.Error(t))
}
}
awaitClose { job.cancel() }
} catch (t: Throwable) {
trySend(StreamEvent.Error(t))
close(t)
}
}
private fun buildPromptForSummary(input: String): String {
return """
Summarize this note into 3 concise bullet points.
Use neutral tone and keep each bullet under 20 words.
Note:
$input
""".trimIndent()
}
}
Notes:
- Use 1.5-Flash for UI-latency-sensitive features; bump to Pro only when necessary and you can tolerate higher latency/cost.
- Set a max token budget and temperature appropriate for deterministic summaries.
Repository: choose Edge vs Cloud at runtime
class SummarizerRepository(
private val edgeChecker: EdgeCapabilityChecker,
private val edge: TextGenerator,
private val cloud: TextGenerator
) {
fun streamSummary(input: String, params: GenerationParams): kotlinx.coroutines.flow.Flow<StreamEvent> =
kotlinx.coroutines.flow.flow {
// Guardrails
val sanitized = sanitizeInput(input)
require(sanitized.isNotBlank()) { "Input is empty after sanitization." }
val useOnDevice = runCatching { edgeChecker.isOnDeviceReady() }.getOrElse { false }
val source = if (useOnDevice) edge else cloud
emitAll(source.streamSummary(sanitized, params))
}
private fun sanitizeInput(input: String): String {
// Boundary control: prevent absurdly large prompts, avoid OOM
val maxChars = 6_000 // tune for your app; align with token limits
return input.trim().take(maxChars)
}
}
ViewModel with cancellation, timeouts, and UI state
data class SummaryUiState(
val inProgress: Boolean = false,
val streamedText: String = "",
val error: String? = null
)
@dagger.hilt.android.lifecycle.HiltViewModel
class SummaryViewModel @javax.inject.Inject constructor(
private val repository: SummarizerRepository,
@javax.inject.Named("defaultParams") private val defaultParams: GenerationParams
) : androidx.lifecycle.ViewModel() {
private val _state = kotlinx.coroutines.flow.MutableStateFlow(SummaryUiState())
val state: kotlinx.coroutines.flow.StateFlow<SummaryUiState> = _state
private var currentJob: kotlinx.coroutines.Job? = null
fun summarize(note: String) {
currentJob?.cancel()
_state.value = SummaryUiState(inProgress = true)
currentJob = viewModelScope.launch {
// Optional timeout for UX responsiveness (tune as needed)
withTimeoutOrNull(15_000L) {
repository.streamSummary(note, defaultParams)
.collect { event ->
when (event) {
is StreamEvent.Token -> {
_state.update { it.copy(streamedText = it.streamedText + event.text) }
}
is StreamEvent.Complete -> {
_state.update { it.copy(inProgress = false, streamedText = event.fullText) }
}
is StreamEvent.Error -> {
_state.update { it.copy(inProgress = false, error = event.throwable.message) }
}
}
}
} ?: run {
_state.update { it.copy(inProgress = false, error = "Timed out. Try again.") }
}
}
}
fun cancel() {
currentJob?.cancel()
_state.update { it.copy(inProgress = false) }
}
override fun onCleared() {
currentJob?.cancel()
}
}
Compose UI that streams cleanly
@Composable
fun SummarizeNoteScreen(
viewModel: SummaryViewModel = androidx.hilt.navigation.compose.hiltViewModel()
) {
val state by viewModel.state.collectAsState()
var noteText by remember { mutableStateOf("") }
Column(modifier = Modifier.padding(16.dp)) {
OutlinedTextField(
value = noteText,
onValueChange = { noteText = it },
label = { Text("Paste note") },
modifier = Modifier.fillMaxWidth().weight(1f, fill = false),
minLines = 6
)
Spacer(Modifier.height(12.dp))
Row {
Button(
onClick = { viewModel.summarize(noteText) },
enabled = noteText.isNotBlank() && !state.inProgress
) { Text("Summarize") }
Spacer(Modifier.width(8.dp))
OutlinedButton(
onClick = { viewModel.cancel() },
enabled = state.inProgress
) { Text("Cancel") }
}
Spacer(Modifier.height(16.dp))
when {
state.inProgress -> {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
Spacer(Modifier.height(8.dp))
Text(
text = state.streamedText.ifBlank { "Generating..." },
style = MaterialTheme.typography.bodyLarge
)
}
state.error != null -> {
Text(
text = state.error ?: "Something went wrong",
color = MaterialTheme.colorScheme.error
)
}
state.streamedText.isNotBlank() -> {
Text(
text = state.streamedText,
style = MaterialTheme.typography.bodyLarge
)
}
}
}
}
Wiring it all up (DI)
@Module
@InstallIn(SingletonComponent::class)
object AiModule {
@Provides
@Singleton
fun provideEdgeCapabilityChecker(
app: Application
): EdgeCapabilityChecker = object : EdgeCapabilityChecker {
override suspend fun isOnDeviceReady(): Boolean {
// Prefer AI Edge SDK’s official readiness check, which may expose:
// - model availability
// - version compatibility
// - minimum device capabilities
// Avoid guessing via package manager.
// return edgeSdk.checkModelReady(model = GeminiNano)
// Placeholder until you wire the real call:
return false
}
override suspend fun reasonIfUnavailable(): String? = null
}
@Provides
@Singleton
@Named("defaultParams")
fun provideDefaultParams(): GenerationParams = GenerationParams(
maxOutputTokens = 256,
temperature = 0.2f
)
@Provides
@Singleton
fun provideEdgeTextGenerator(app: Application): TextGenerator =
EdgeTextGenerator(app)
@Provides
@Singleton
fun provideCloudTextGenerator(): TextGenerator =
CloudTextGenerator(
apiKey = BuildConfig.GEMINI_API_KEY,
modelName = "gemini-1.5-flash"
)
@Provides
@Singleton
fun provideSummarizerRepository(
checker: EdgeCapabilityChecker,
edge: TextGenerator,
cloud: TextGenerator
): SummarizerRepository = SummarizerRepository(checker, edge, cloud)
}
Security note: Store API keys securely (do not hardcode). Use remote config or secure storage, and apply network privacy best practices. For on-device/Nano-only experiences, you do not need an API key.
Prompt engineering for on-device
- Keep prompts short, explicit, and deterministic. Lower temperature.
- Constrain output with explicit format (e.g., “3 bullet points”, length limits).
- Pre-truncate inputs to a safe size.
- Avoid complex multi-step instructions that explode token usage and latency.
Example prompt snippet (used above):
- “Summarize into 3 concise bullet points”
- “Each bullet under 20 words”
- “Neutral tone; focus on key facts and decisions”
Performance, UX, and reliability
- Warm-up: First request may be slower as the model initializes. Consider lazy pre-warm when user navigates to the screen.
- Streaming: Always stream to keep the UI alive; avoid waiting for the final token for first paint.
- Cancellation: Support cancellation when navigating away or if the user edits text mid-generation.
- Timeouts: Use a user-facing timeout; surface actionable failures (“Model not available offline”, “Timed out”, “No network”).
- Battery and thermal: Don’t loop long generations in the background; use the SDK’s guidance for batching and scheduling. Prefer generating during user interaction, not in the background.
Privacy and data handling
- On-device path: Data stays on-device; no internet needed. Communicate this clearly in your UX for sensitive notes.
- Cloud fallback: Clearly disclose network usage and handle PII responsibly (consent, redaction).
- Logging: Never log raw user content in production logs. Gate debug logs behind build flags.
Testing strategy
- Unit test repository selection logic (Edge available vs not).
- Contract test the provider interface with fake generators that emit controlled streams.
- Integration test on devices with and without Nano support.
- Load test with large notes to uncover memory/latency issues.
- UI tests: Assert that streaming renders incrementally and that Cancel works.
Common mistakes and how to fix them
- Model not ready on-device:
- Symptom: Immediate error from Edge SDK or null client/session.
- Fix: Use the SDK’s readiness check and expose a “Download/Enable” affordance or auto-fallback to cloud. Avoid relying on package presence checks.
- Jank during first token:
- Symptom: 200–600 ms UI hitch when session warms up.
- Fix: Pre-warm lazily (e.g., when screen becomes visible) on a background dispatcher. Reuse sessions.
- OOM or ANR with huge inputs:
- Symptom: Memory spikes or freezes processing long notes.
- Fix: Enforce strict input size limits. Chunk and summarize incrementally if needed (map-reduce pattern).
- No token streaming in UI:
- Symptom: Empty UI until completion.
- Fix: Ensure you’re using the streaming API; append partial tokens; flush to Compose state.
- Timeout too aggressive:
- Symptom: Frequent timeouts on low-end devices.
- Fix: Increase timeout and/or reduce max output tokens. Consider device-class heuristics.
- Cloud API key exposed:
- Symptom: Static key in client or VCS.
- Fix: Use server-side proxy or secured remote config, obfuscation, and app attestation.
Rolling out safely
- Feature flags: Gate the entire feature behind a remote flag for staged rollout.
- Device targeting: Gradually enable on supported devices first.
- Metrics: Track latency, token count, session warm-up time, error rates, cloud fallback rate, and cancellations.
- Crash/ANR monitoring: Pay attention to OOM signatures and binder-related issues if the Edge SDK uses a system service.
When to choose on-device vs cloud
-
On-device (Gemini Nano) is ideal for:
- Short-form generation and rewriting (summaries, smart replies, autofill hints)
- Privacy-sensitive content
- Latency-critical UX
- Offline and spotty connectivity
-
Cloud (Gemini API) is better for:
- Larger context windows
- Heavier reasoning or multimodal tasks
- Team workflows where server-side policy and auditing are required
A hybrid approach (as we implemented) is the most resilient.
Final notes on the AI Edge SDK integration
Because the AI Edge SDK and AICore are evolving, refer to the official SDK documentation for:
- Exact Gradle artifacts and versions
- Model/download readiness APIs
- Client/session construction code and lifecycle
- Streaming function names and cancellation hooks
- Supported Android/Device matrix and required permissions (generally none additional for on-device)
Keep all these calls isolated in your EdgeTextGenerator and EdgeCapabilityChecker. This limits churn when you upgrade the SDK.
Key takeaways
- On-device LLMs like Gemini Nano unlock responsive, private, and offline-friendly features.
- Architect behind a small TextGenerator interface to swap Edge and Cloud without refactoring.
- Stream results to the UI for fast first paint; handle cancellation, timeouts, and input limits.
- Proactively check model readiness and implement a clean cloud fallback path.
- Treat performance, privacy, and reliability as first-class concerns - just like any other production feature.
Next steps
- Wire the AI Edge SDK client code into
EdgeTextGeneratorusing the latest docs and test on a Nano-capable device. - Add a WorkManager task to prime model readiness on unmetered Wi‑Fi and charging.
- Extend the feature with “Actionable Summary” output format (e.g., JSON with decisions, dates, and owners) and render structured chips in the UI.
- Measure and optimize: instrument warm-up time, token throughput, and fallback frequency; iterate on prompts and parameters for quality and speed.
