Private notes summarizer with on-device Gemini Nano
What you will build
The finished app lets a user write, store, and manage private notes entirely on their phone. Each note can be summarised into bullet points or proofread without leaving the device, using the ML Kit GenAI Summarization and Proofreading APIs, which run Gemini Nano through Android AICore on supported devices only. The app checks feature status before any AI call, downloads the feature when needed with progress, and shows a clear fallback when the device is unsupported. All note text stays in Room; nothing is sent to a server unless the user explicitly opts into a cloud path behind a consent screen.
For an employer, this project shows you can integrate on-device generative AI with proper feature detection, handle async model downloads, respect platform limits (foreground only, per-app quotas), design a clean fallback, test with a fake interface, and measure real latency. It proves comfort with Jetpack Compose state, Room persistence, Kotlin coroutines, and the trade-offs between on-device and cloud AI.
Skills you practise
- On-device feature detection and model download with ML Kit GenAI
- Jetpack Compose state management with StateFlow and MVI
- Room persistence for offline-first note storage
- Bridging callback and future-based APIs into coroutines and Flow
- Fallback design and explicit user consent for cloud paths
- Testing with a fake interface instead of the real model
- Latency measurement and privacy-safe logging on mobile
Architecture
The app follows unidirectional data flow. Compose screens (note list, note editor, summary sheet) read a StateFlow<UiState> from a ViewModel. The ViewModel talks to a NoteAi interface; the production implementation wraps ML Kit's Summarization.getClient(...) and Proofreading.getClient(...), while tests inject a FakeNoteAi. All note text lives in Room behind a NoteRepository; the ViewModel never calls Room directly.
Before showing the AI buttons, the ViewModel asks NoteAi for the feature status, which comes from checkFeatureStatus() and is one of FeatureStatus.UNAVAILABLE, DOWNLOADABLE, DOWNLOADING, or AVAILABLE. When it is DOWNLOADABLE, the UI offers a download button that calls downloadFeature with a DownloadCallback, bridged into a Flow of progress events. When it is UNAVAILABLE, the UI shows a fallback message and, only if the user has consented, routes to an optional cloud path through your own backend. Inference runs only while the app is the top foreground app; AICore blocks background use and enforces per-app quotas, which surface as GenAiException error codes. Latency is measured at the NoteAi boundary and logged without note text.
| Module or layer | Responsibility |
|---|---|
| UI (Compose screens) | Note list, editor, and summary screens. Render UiState, emit user intents. No business logic. |
| ViewModel + MVI | Holds UiState as a StateFlow. Calls NoteAi and NoteRepository. Maps results and error codes to UI states. Starts AI work only from user actions on a visible screen. |
| NoteAi interface + implementations | Abstraction over ML Kit GenAI summarisation and proofreading: status, download, summarize, proofread. MlKitNoteAi for production, FakeNoteAi for tests. |
| NoteRepository + Room | Single source of truth for note text. CRUD operations. No AI logic. No network calls. |
| Feature detection + fallback | Maps FeatureStatus to an app status, drives the download, and decides on-device vs consented cloud vs unavailable. |
| Consent + settings | Stores consent for the optional cloud path in DataStore. No API keys in the app; the cloud path goes through your backend. |
Milestones
1. Notes CRUD with Compose and Room
Create, read, update, and delete notes stored in Room, shown in a Compose list and editor.
- Add Room and define a
Noteentity with id, title, body, and updated timestamp. - Write a
NoteDaowith insert, update, delete, and aFlow<List<Note>>query for the list screen. - Build a
NoteListScreenwithLazyColumnand aNoteEditorScreenwith aTextField, wired with Navigation Compose. - Create a
NoteRepositorythat wraps the DAO; the ViewModel never calls Room directly. - Add a
NoteViewModelthat exposesStateFlow<UiState>and handles create, edit, and delete intents.
Done when: You can add a note, see it in the list, edit it, delete it, and the list is still there after the process is killed and restarted.
Lessons: room entities daos queries, mvi in practice, navigation in compose
2. Feature status and model download
Detect whether summarisation is unavailable, downloadable, downloading, or available, and download it from the UI.
- Add the
com.google.mlkit:genai-summarizationandcom.google.mlkit:genai-proofreadingdependencies, pluskotlinx-coroutines-guavaso you canawait()the returned futures. - Build
SummarizerOptions.builder(context)with an input type, output type (one, two, or three bullets), and language, then create the client withSummarization.getClient(options). - Call
summarizer.checkFeatureStatus().await()and map the fourFeatureStatusvalues to a sealedAiStatustype. - When the status is
DOWNLOADABLE, show a "Download model" button that callsdownloadFeaturewith aDownloadCallback; wrap it incallbackFlowand emit started, progress, completed, and failed events. - Check the status again when the screen resumes, since a download may have finished or failed while the app was away. Close the clients in
onCleared().
Done when: On a supported device the status moves from DOWNLOADABLE to AVAILABLE after you tap download, with visible progress; on an unsupported device it stays UNAVAILABLE and the UI shows a clear message.
Lessons: ml kit ready made on device ml, on device llms gemini nano and litert lm, error handling and result types
3. Summarisation and proofreading in the foreground
Run summarisation and proofreading on the current note while the screen is visible, show a loading state, and display the result.
- Define a
NoteAiinterface withsuspend fun status(): AiStatus,fun download(): Flow<DownloadEvent>,suspend fun summarize(text: String): String, andsuspend fun proofread(text: String): String. - Implement summarisation with
SummarizationRequest.builder(text).build()andsummarizer.runInference(request).await().summary, or use the streamingrunInference(request) { newText -> ... }overload to show text as it arrives. - Implement proofreading with
ProofreaderOptions(input typeKEYBOARDorVOICE, plus a language),Proofreading.getClient, andProofreadingRequest; show the top suggestion fromresults. Proofreading accepts only short input, so send one paragraph at a time. - Only start AI work from a button tap on the visible editor, and launch it in
viewModelScopeso leaving the screen cancels waiting for the result. - Measure latency with
SystemClock.elapsedRealtime()before and after each call and show it in a small label.
Done when: Tapping "Summarise" on a long note shows a progress indicator, then bullet points with a latency label. Tapping "Proofread" on a paragraph shows a corrected version the user can accept or dismiss.
Lessons: latency cost and fallbacks, stateflow and sharedflow, collecting flows safely in the ui
4. Fallback path and explicit user consent
When on-device AI is unavailable, show a clear message and offer an optional cloud path only after the user consents.
- Add a
ConsentStorebacked by DataStore that holds one boolean:cloudAiConsented. - When
AiStatusisUNAVAILABLE, show "On-device AI is not available on this device." with an optional "Use cloud" button. Notes, editing, and search keep working without AI. - The cloud button opens a consent screen explaining that note text will leave the device. No cloud call happens before consent is stored.
- Route the cloud path through your own backend (or Firebase AI Logic with App Check); never put a provider API key in the app.
- Add a settings toggle where the user can revoke consent at any time.
Done when: On a device where checkFeatureStatus() returns UNAVAILABLE, the user sees the fallback message. The cloud path is never reached without an explicit consent tap. Revoking consent disables the cloud path immediately.
Lessons: on device vs cloud ai how to choose, privacy safety and content filtering, calling claude and other llm apis through your backend
5. Tests with a fake NoteAi
Write unit tests that exercise every AI state without a real model, using a FakeNoteAi.
- Create
FakeNoteAiwith a configurable status, a scripted download flow, and a configurable result or exception forsummarizeandproofread. - Write a
NoteViewModelTestthat injects the fake and asserts theUiStatetransitions: idle, loading, success, and error. - Add a test for the busy or quota path: the fake throws your own
AiBusyException, and the UI shows a "try again later" message instead of a crash. - Add tests for
UNAVAILABLE(fallback state) and for a download that fails (retry button, no endless spinner). - Run the suite with
./gradlew testand confirm it passes on a machine without any device.
Done when: NoteViewModelTest covers success, busy or quota error, unavailable, failed download, and empty note, and no test touches a real ML Kit client.
Lessons: fakes vs mocks, testing coroutines and flows, test pyramid for android
6. Quota errors, logging, and hardening
Handle platform errors gracefully, record latency without leaking note text, and verify the privacy guarantee.
- Catch
GenAiExceptioninMlKitNoteAiand maperrorCode:ErrorCode.BUSY(too many requests in a short time) to retry with exponential backoff,ErrorCode.PER_APP_BATTERY_USE_QUOTA_EXCEEDED(longer-duration quota) to a "try again later" state, andErrorCode.BACKGROUND_USE_BLOCKEDto a "reopen the app" state. - Add a
LatencyLoggerthat records timestamp, operation, latency, and status, plus the note id but never the body. - Handle long notes: enable
setLongInputAutoTruncationEnabled(true)on the summarizer options or split the note and summarise the parts. - Audit the code: confirm no note body is passed to any network call unless
cloudAiConsentedis true, and none reaches logs or crash reports. - On a supported device, download the feature, run several summaries, and read the log to see the latency spread.
Done when: Busy and quota errors show a specific message instead of a crash or a generic error. The log contains latency entries with no note text. A search of the codebase shows no note body reaching a network call when consent is off.
Lessons: evaluating ai features, performance monitoring in production, crash handling and reporting
Key code
import android.content.Context
import com.google.mlkit.genai.common.DownloadCallback
import com.google.mlkit.genai.common.FeatureStatus
import com.google.mlkit.genai.common.GenAiException
import com.google.mlkit.genai.summarization.Summarization
import com.google.mlkit.genai.summarization.SummarizationRequest
import com.google.mlkit.genai.summarization.SummarizerOptions
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.guava.await
enum class AiStatus { UNAVAILABLE, DOWNLOADABLE, DOWNLOADING, AVAILABLE }
sealed interface DownloadEvent {
data class Started(val bytesToDownload: Long) : DownloadEvent
data class Progress(val bytesDownloaded: Long) : DownloadEvent
data object Completed : DownloadEvent
}
interface NoteSummarizer : AutoCloseable {
suspend fun status(): AiStatus
fun download(): Flow<DownloadEvent>
suspend fun summarize(text: String): String
}
class MlKitNoteSummarizer(context: Context) : NoteSummarizer {
private val summarizer = Summarization.getClient(
SummarizerOptions.builder(context)
.setInputType(SummarizerOptions.InputType.ARTICLE)
.setOutputType(SummarizerOptions.OutputType.THREE_BULLETS)
.setLanguage(SummarizerOptions.Language.ENGLISH)
.setLongInputAutoTruncationEnabled(true)
.build()
)
override suspend fun status(): AiStatus =
when (summarizer.checkFeatureStatus().await()) {
FeatureStatus.AVAILABLE -> AiStatus.AVAILABLE
FeatureStatus.DOWNLOADING -> AiStatus.DOWNLOADING
FeatureStatus.DOWNLOADABLE -> AiStatus.DOWNLOADABLE
else -> AiStatus.UNAVAILABLE
}
override fun download(): Flow<DownloadEvent> = callbackFlow {
summarizer.downloadFeature(object : DownloadCallback {
override fun onDownloadStarted(bytesToDownload: Long) {
trySend(DownloadEvent.Started(bytesToDownload))
}
override fun onDownloadProgress(totalBytesDownloaded: Long) {
trySend(DownloadEvent.Progress(totalBytesDownloaded))
}
override fun onDownloadCompleted() {
trySend(DownloadEvent.Completed)
close()
}
override fun onDownloadFailed(e: GenAiException) {
close(e) // the collector sees the failure, so the UI can show retry
}
})
awaitClose { }
}
// Call only from a user action while the app is in the foreground.
override suspend fun summarize(text: String): String {
val request = SummarizationRequest.builder(text).build()
return summarizer.runInference(request).await().summary
}
override fun close() = summarizer.close()
}
class FakeNoteSummarizer(
var currentStatus: AiStatus = AiStatus.AVAILABLE,
var result: Result<String> = Result.success("- Fake summary"),
) : NoteSummarizer {
override suspend fun status() = currentStatus
override fun download(): Flow<DownloadEvent> = callbackFlow {
trySend(DownloadEvent.Completed)
close()
awaitClose { }
}
override suspend fun summarize(text: String) = result.getOrThrow()
override fun close() {}
}NoteSummarizeris the summarisation half ofNoteAi; proofreading follows the same pattern withProofreading.getClient.checkFeatureStatus(),runInference(), anddownloadFeature()returnListenableFutures;kotlinx-coroutines-guavasuppliesawait()so they read as suspend calls. The ViewModel catchesGenAiExceptionand maps itserrorCodeto UI state.callbackFlowturnsDownloadCallbackinto aFlow.onDownloadFailedcloses the flow with the exception, so a failed download ends in an error state instead of an endless spinner.setLongInputAutoTruncationEnabled(true)lets the summarizer cut input that is over its limit instead of failing. Very short notes may be rejected for the article input type, so hide the button for them.- The fake implements the same interface, so ViewModel tests can script every status, download outcome, and error without a device, AICore, or Gemini Nano.
Pitfalls
- Calling the GenAI APIs from WorkManager, a service, or when the app is in the background. Inference is allowed only when your app is the top foreground app; anything else, including a foreground service, fails with
ErrorCode.BACKGROUND_USE_BLOCKED. Fix: start AI work only from user actions on a visible screen, and treat that error as "reopen the app". - Skipping the status check. On an unsupported device the feature is
UNAVAILABLEand inference fails; on a supported device the feature may still need downloading. Fix: callcheckFeatureStatus()first and branch on all four values, and check again when the screen resumes. - Putting a cloud API key in
local.propertiesorBuildConfig. Anything in the APK can be extracted. Fix: the optional cloud path goes through your own backend or through Firebase AI Logic with App Check, and the app never holds a provider key. - Treating quota errors as generic failures. AICore enforces per-app quotas:
ErrorCode.BUSYafter too many requests in a short time andErrorCode.PER_APP_BATTERY_USE_QUOTA_EXCEEDEDfor longer-duration limits. Fix: back off exponentially onBUSY, show a clear "try again later" message for the longer quota, and never retry in a tight loop. - Blocking the main thread on the futures. Calling
.get()on the returnedListenableFuturefrom the main thread freezes the UI until inference finishes. Fix:await()it from a coroutine, or use the streamingrunInferencecallback. - Logging the full note body. The whole point is that notes stay on the device; logging the body to a file, Logcat, or a crash reporter defeats it. Fix: log only the note id, operation, latency, and status.
Code review finding
- The user taps "Download model" and the UI switches to a progress indicator.
- The
DownloadCallbackimplementation handlesonDownloadCompletedbut leavesonDownloadFailedempty. - When the network drops,
onDownloadFailedfires, nothing changes in UiState, and the spinner never ends. - When the user comes back later, the screen never calls
checkFeatureStatus()again, so it does not notice the status changed.
- Close the
callbackFlowwith the exception inonDownloadFailed, catch it in the ViewModel, and show a "Retry download" button. - Call
checkFeatureStatus()again when the screen resumes and update the UI from the fresh value. - Add a unit test where
FakeNoteSummarizer.download()fails and assert the UI ends in the retry state, not loading.
Stretch goals
- Show proofreading suggestions inline in the editor with an
AnnotatedStringthat highlights changed words. - Stream the summary into the UI with the callback overload of
runInferenceinstead of waiting for the full result. - Add the ML Kit GenAI Rewriting API to offer tone changes (for example, more formal or shorter) for a note.
- Write a one-page design doc comparing on-device and cloud for this use case, covering privacy and device coverage, and link it from the README.
- Add screenshot tests for the fallback screen and the consent screen so the fallback path is checked in CI.
Done checklist
- Every AI call is preceded by a
checkFeatureStatus()check, and all fourFeatureStatusvalues are handled. downloadFeatureuses aDownloadCallbackwhose failure path leads to a retry state.- AI work starts only from user actions on a visible screen; nothing runs from WorkManager or a service.
- Busy, quota, and background-blocked
GenAiExceptioncodes each show a specific message. - Summarisation and proofreading sit behind an interface, and the ViewModel tests use the fake without a device.
- Unsupported devices get a clear fallback; the cloud path is unreachable without stored consent and holds no API key in the app.
- No note body appears in any network call (without consent), log line, or crash report.
- The ML Kit clients are closed when the ViewModel is cleared.
Talking about it in an interview
- Explain why the AI sits behind an interface: it decouples the ViewModel from ML Kit, lets you test every state with a fake, and makes it easy to add a cloud implementation later without touching the UI.
- Walk through the feature-detection flow: check status, branch on four values, download only on a user tap with progress, and re-check on resume. Emphasise that on-device generative AI exists only on some devices, so the app must be complete without it.
- Describe the platform limits: inference only when the app is in the foreground, and per-app quotas that return
BUSYor a longer-duration quota error. Explain how each maps to UI and why you back off rather than retry in a loop. - Describe the privacy decision: notes stay in Room, the cloud path is opt-in and goes through a backend, and logs hold ids and latencies, not text. Frame it as a product decision as well as a technical one.
- Mention the testing strategy: a fake rather than a mock, because you want scripted, readable behaviour for status, download, and errors. Contrast this with a mock and say when you would choose one.