nano – Code Guilds https://codeguilds.com Fri, 24 Jul 2026 22:27:58 +0000 en-US hourly 1 https://wordpress.org/?v=7.1.5 Build Intelligent Android Apps: Leveraging Gemini Nano and ML Kit for On-Device Personalization https://codeguilds.com/build-intelligent-android-apps-leveraging-gemini-nano-and-ml-kit-for-on-device-personalization/ https://codeguilds.com/build-intelligent-android-apps-leveraging-gemini-nano-and-ml-kit-for-on-device-personalization/#respond Fri, 24 Jul 2026 22:27:58 +0000 https://codeguilds.com/build-intelligent-android-apps-leveraging-gemini-nano-and-ml-kit-for-on-device-personalization/ The Android development landscape is undergoing a significant transformation, moving beyond mere functionality to embrace intelligent, personalized, and agentic user experiences. In a series of insightful blog posts, Google’s Android Developers team has been meticulously detailing this evolution, showcasing how to imbue basic Android applications with advanced AI capabilities. The latest installment delves into the practical application of on-device intelligence, demonstrating how developers can harness the power of Gemini Nano through ML Kit’s Prompt API to create sophisticated, privacy-centric features directly on user devices. This approach not only enhances user experience but also addresses critical concerns around data privacy and real-time processing.

The foundation of this intelligent transformation lies in the ability to process prompts and data locally, eliminating the need to send sensitive information to remote servers. This on-device processing offers a compelling array of advantages, including enhanced privacy and security, as user data remains within the device’s secure environment. Furthermore, it significantly reduces latency, enabling near-instantaneous responses and a more fluid user interaction. Offline functionality is another key benefit, ensuring that intelligent features remain accessible even without an active internet connection, a crucial consideration for travelers or users in areas with unreliable network coverage. Finally, on-device processing can lead to cost efficiencies by minimizing reliance on cloud-based AI services, which often incur usage-based charges.

Building upon the foundation laid in the introductory post of this series, which introduced "Jetpacker" – a demo application serving as the canvas for these AI integrations – this article focuses on three specific features designed to elevate the user experience within Jetpacker: summarizing trip itineraries, managing expenses, and capturing voice notes. These features, when implemented with on-device intelligence, promise to make travel planning and management significantly more intuitive and efficient.

Build intelligent Android apps: On-device inference

Enhancing Trip Planning with Intelligent Itinerary Summarization

For travelers, a well-structured itinerary is essential, but an abundance of detailed information can often lead to an overwhelming user experience. The Jetpacker app addresses this challenge by introducing an intelligent "Get ready for your trip" section at the top of its itinerary screen. This feature leverages the power of Large Language Models (LLMs) to condense complex itineraries into easily digestible summaries.

By feeding a trip’s itinerary into an LLM, the application can generate a concise overview of the trip’s essence, coupled with practical advice such as packing tips and relevant local phrases. This is a prime candidate for on-device implementation due to several factors. Firstly, the summarization of text is a computationally feasible task for modern mobile processors. Secondly, and crucially, itineraries can often contain personal details, making on-device processing a significant privacy advantage. Users can be assured that their travel plans are not being transmitted to external servers for analysis.

The engine behind this intelligent summarization is Gemini Nano, Google’s most efficient AI model specifically engineered for mobile devices. Launched a few years prior, Gemini Nano has already seen widespread adoption, powering intelligent features on over 140 million devices. The latest iteration, Gemini Nano 4, builds upon the architectural advancements of the recently released Gemma 4 model, further optimizing for battery life and overall performance efficiency. This makes it an ideal choice for integrating advanced AI capabilities into mobile applications without compromising the user’s device performance or battery longevity.

Developers can harness Gemini Nano 4’s capabilities through ML Kit’s Prompt API. This API allows for the creation of prompts that instruct the model to perform specific tasks. For the itinerary summarization feature, a prompt is crafted to include the trip itinerary and request a summary, preparation tips, and useful phrases. The process involves defining a configuration for Gemini Nano 4, specifying parameters like the release stage and performance preference. The generationConfig block in the provided code snippet illustrates how to set up the model for preview, prioritizing speed with ModelPreference.FAST.

Build intelligent Android apps: On-device inference

The crucial step of prompt engineering often requires iteration to achieve optimal results. Google’s AICore app, accessible via a developer preview, plays a vital role in this iterative process. By enabling the AICore developer preview, users can download and test preview models like Gemini Nano 4, allowing them to refine prompts and evaluate model outputs in real-time. Through such iterations, the development team successfully reduced the response time for itinerary summarization from an initial 13 seconds to under 2 seconds, demonstrating the impact of effective prompt design and the performance gains of on-device models. The full code implementation and optimized prompt for this feature are available for developers to explore in the Jetpacker GitHub repository.

Streamlining Expense Management with On-Device Data Extraction

The second intelligent feature introduced in Jetpacker is a simplified expense manager, aimed at automating the tedious process of sifting through receipts and calculating budgets. This feature addresses a common pain point for travelers and individuals alike, offering a more streamlined approach to financial tracking.

A key consideration for any expense management tool is the potential for sensitive data to be present on receipts, such as credit card numbers and personal addresses. This makes on-device processing a highly attractive solution, ensuring that such private information is handled locally and never leaves the user’s device. This aligns with the growing user demand for enhanced data privacy and security in their mobile applications.

Gemini Nano 4’s enhanced multimodal capabilities, particularly its proficiency in image understanding tasks like Optical Character Recognition (OCR) and visual data extraction, make it exceptionally well-suited for processing receipts. The model can accurately extract relevant information from images, such as the name of the establishment, the total amount spent, and the category of the expense.

Build intelligent Android apps: On-device inference

To facilitate the seamless integration of extracted data into the application, ML Kit’s Structured Output API is employed. This API allows the LLM to output information directly into a defined Kotlin data object, eliminating the need for manual parsing of unstructured text. The ParsedReceipt data class, annotated with @Generable and @Guide to guide the model’s output, exemplifies this approach. The prompt instructs the model to identify receipts, extract key information, and categorize the expense, with specific guidance on the format and content of each field. The ModelPreference.FULL is utilized in this scenario, prioritizing the model’s reasoning power for accurate data extraction from potentially complex receipt images. The code snippet demonstrates how to create a generateContentRequest with an ImagePart and a TextPart for the prompt, then uses generateTypedContentRequest to specify the desired structured output.

Empowering Voice Notes with On-Device Transcription and Categorization

The final intelligent feature developed for Jetpacker is a fully on-device voice notes capability, designed to help users easily record and manage audio memos during their trips. This feature combines the power of ML Kit’s Speech Recognition API with the Prompt API to provide a seamless audio-to-text experience.

The ML Kit GenAI Speech Recognition API offers two distinct modes for on-device transcription. The Basic mode, available on most Android devices with API level 31 and higher, utilizes a traditional on-device speech recognition model. For enhanced performance, broader language coverage, and superior transcription quality, the Advanced mode leverages Gemini Nano, currently supported on Pixel 10 devices.

For the Jetpacker application, the Advanced mode is employed to ensure the highest quality transcription. The process begins with setting up the SpeechRecognizerOptions, specifying the locale and prioritizing the advanced mode. The SpeechRecognizer client is then initialized. The transcribeVoiceNote function uses a SpeechRecognizerRequest to capture audio from the device’s microphone. As the user speaks, the API provides real-time PartialTextResponse updates, offering a preview of the transcription. Upon completion of recording, a FinalTextResponse delivers the full transcribed text.

Build intelligent Android apps: On-device inference

Following transcription, the system utilizes the ML Kit GenAI Prompt API to process the transcribed voice note. The prompt is designed to take the transcribed text and a list of trip events, then refine the transcription by removing filler words and, crucially, identify which of the provided trip events the voice note relates to. This allows users to easily associate their audio memos with specific activities within their itinerary, providing a contextualized recap of their trip. The code snippet illustrates how the processAndCategorizeVoiceNote function constructs a prompt that feeds both the transcribed text and the trip events to the LLM for analysis and categorization.

The Broader Impact of On-Device AI on Android Development

The successful integration of these three intelligent features into the Jetpacker app underscores a significant trend in Android development: the increasing feasibility and desirability of on-device AI. By leveraging Google’s cutting-edge AI models like Gemini Nano and the robust toolkit provided by ML Kit, developers can now build sophisticated, personalized, and agentic experiences that were once the exclusive domain of cloud-based systems.

The implications of this shift are far-reaching. For users, it means more private, responsive, and offline-capable applications. For developers, it opens up new avenues for innovation, enabling them to create richer user interactions without the complexities and costs associated with extensive cloud infrastructure. The privacy-first approach inherent in on-device processing is particularly timely, as users become increasingly aware of and concerned about their digital footprint.

This series of blog posts serves as a comprehensive guide, not just for Jetpacker, but for any developer looking to infuse their Android applications with intelligence. The progression from Part 1 (introduction to the app and high-level overview) to Part 2 (this deep dive into on-device intelligence) sets the stage for subsequent discussions on hybrid and cloud reasoning (Part 3), system integration with AppFunctions (Part 4), and the development of in-app agentic workflows (Part 5, forthcoming).

Build intelligent Android apps: On-device inference

The availability of the full source code for Jetpacker on GitHub and accompanying video resources provides invaluable practical guidance. As Android continues its trajectory towards more intelligent and personalized user experiences, understanding and implementing on-device AI capabilities, as demonstrated in this exploration of Gemini Nano and ML Kit, will be crucial for developers seeking to build the next generation of groundbreaking applications.

The commitment to empowering developers with these advanced tools signifies Google’s dedication to fostering innovation within the Android ecosystem. By providing accessible and powerful AI solutions, the platform is poised to witness a surge in intelligent applications that not only enhance user productivity and enjoyment but also uphold the highest standards of data privacy and security.

]]>
https://codeguilds.com/build-intelligent-android-apps-leveraging-gemini-nano-and-ml-kit-for-on-device-personalization/feed/ 0
Build Intelligent Android Apps with On-Device Gemini Nano and ML Kit https://codeguilds.com/build-intelligent-android-apps-with-on-device-gemini-nano-and-ml-kit/ https://codeguilds.com/build-intelligent-android-apps-with-on-device-gemini-nano-and-ml-kit/#respond Thu, 23 Jul 2026 10:27:47 +0000 https://codeguilds.com/build-intelligent-android-apps-with-on-device-gemini-nano-and-ml-kit/ The Android developer community is witnessing a significant evolution in mobile application capabilities, with a renewed focus on empowering developers to create truly personalized, intelligent, and agentic user experiences. This shift is exemplified by the ongoing "Build intelligent Android apps" blog post series, which systematically transforms a basic Android application into a sophisticated AI-driven tool. Following an introductory post that unveiled "Jetpacker," the demo application serving as the series’ cornerstone, the latest installment delves into the practical implementation of on-device intelligence using Google’s Gemini Nano and the robust ML Kit Prompt API. This article explores how developers can harness these cutting-edge technologies to imbue their Android applications with advanced, privacy-centric features that operate directly on the user’s device.

The Power of On-Device Processing for Enhanced User Experiences

At its core, building intelligent on-device features signifies the capacity of an application to process prompts and data locally, bypassing the need for constant data transmission to external servers. This architectural approach offers a compelling suite of advantages that directly translate to a superior user experience. Firstly, enhanced privacy and security are paramount. By keeping sensitive user data on the device, the risk of data breaches during transit or from cloud storage is significantly mitigated, fostering greater user trust. Secondly, reduced latency is a critical benefit. Eliminating the round trip to a server means that AI-powered responses are delivered almost instantaneously, crucial for real-time interactions and applications demanding immediate feedback. Thirdly, offline functionality becomes a reality. Applications can continue to provide intelligent features even in environments with limited or no internet connectivity, expanding their usability and reach. Finally, cost efficiency is a tangible advantage for developers. Reducing reliance on cloud-based AI services can lead to substantial savings on server infrastructure and API usage fees.

Recognizing these benefits, the Jetpacker application has been enhanced with three key on-device features designed to elevate user engagement: the intelligent summarization of trip itineraries, streamlined expense management, and efficient voice note capture. These features demonstrate the tangible impact of integrating advanced AI models directly into the mobile ecosystem.

Intelligent Itinerary Summarization: From Overload to Insight

Build intelligent Android apps: On-device inference

Travel planning often involves navigating a wealth of information, from flight schedules and hotel bookings to daily activities and local attractions. The itinerary screen within the Jetpacker app, designed to provide a comprehensive overview of a trip, can quickly become overwhelming for users. To address this, a new "Get ready for your trip" section has been introduced, offering a concise and actionable summary powered by AI.

This feature leverages Gemini Nano, Google’s most efficient AI model specifically optimized for mobile devices. First introduced several years ago, Gemini Nano has since seen widespread adoption, now operating on over 140 million devices globally. The latest iteration, Gemini Nano 4, builds upon the architectural foundation of the recently released Gemma 4 model, further refining its capabilities for maximum battery and performance efficiency.

The implementation utilizes ML Kit’s Prompt API, allowing developers to harness Gemini Nano 4’s advanced model capabilities for prototyping on-device features. The process involves crafting a prompt that feeds the trip itinerary to the model, requesting it to generate a personalized summary, along with practical preparation tips and relevant local phrases.

A typical prompt structure might look like this:

// Dependency declaration for ML Kit's GenAI Prompt API
// implementation("com.google.mlkit:genai-prompt:1.0.0-beta3")

// Configuration for the Gemini Nano 4 E2B preview model, prioritizing speed.
val previewFastConfig = generationConfig 
    modelConfig = modelConfig 
        releaseStage = ModelReleaseStage.PREVIEW
        preference = ModelPreference.FAST
    


// Obtain a client for the Gemini Nano 4 preview model.
val geminiNano2BPreviewModel = Generation.getClient(previewFastConfig)

// Placeholder for the trip itinerary data.
val tripItinerary = "Day 1: Arrive in Paris, check into hotel. Evening Eiffel Tower visit. Day 2: Louvre Museum, Notre Dame Cathedral. Day 3: Montmartre, Sacré-Cœur Basilica. Depart in the evening."

// Constructing the prompt to generate a summary, preparation tips, and useful phrases.
val getReadyForYourTripSummary = geminiNano2BPreviewModel
 .generateContent("Given this trip itinerary: $tripItinerary,
     generate the following: overall vibe, tips on how to prepare for this
     trip, and common short phrases to learn for the trip.")

The iteration process for finding the optimal prompt is crucial for achieving desired results. Tools like the AICore app, which allows developers to opt into a developer preview and download preview models like Gemini Nano 4, are invaluable for testing prompts and observing model outputs. Through diligent refinement, the response time for itinerary summarization in Jetpacker was dramatically reduced from an initial 13 seconds to under two seconds, a testament to the efficiency gains achievable with on-device AI. The final code implementation and prompt details can be found in the Jetpacker repository on GitHub.

Local Processing for Sensitive User Input: The Expense Manager

Build intelligent Android apps: On-device inference

Enhancing the travel experience further involves simplifying the often tedious task of managing expenses. The Jetpacker app now features a simple expense manager that aims to automate the process of sorting receipts and calculating budgets. This is particularly relevant given that receipts can contain sensitive personal information, such as credit card numbers and addresses.

The decision to implement this feature on-device is driven by the need to safeguard user privacy. By processing receipt data locally, users can be assured that their sensitive financial information remains on their device and is not transmitted to any external servers. This adherence to privacy-by-design principles is a cornerstone of modern mobile application development.

Furthermore, Gemini Nano 4’s enhanced multimodal capabilities, especially in image understanding tasks like Optical Character Recognition (OCR) and visual data extraction, make it an ideal solution for extracting information from receipts. For this use case, the prompt is designed to analyze an image of a receipt and extract key details such as a generated title, the total amount spent, and the category of the expense.

To ensure the model outputs this information in a structured and easily parsable format, ML Kit’s Structured Output API is employed. This allows for the seamless generation of a Kotlin data object, pre-defined by the developer.

The structured output definition might appear as follows:

// Dependencies for ML Kit's GenAI Prompt and Schema Compiler
// implementation("com.google.mlkit:genai-prompt:1.0.0-beta3")
// ksp("com.google.mlkit:genai-schema-compiler:1.0.0-alpha1")

// Data class defining the expected output structure for parsed receipt information.
@Generable("Information extracted from an expense receipt")
data class ParsedReceipt(
  @Guide("Generated title for the expense less than 6 words. Based on restaurant or activity name.")
  val  String,
  @Guide("Total amount of the expense. Look for values at the bottom and words like total or balance due.")
  val amount: Double,
  @Guide("Type of expense", enumValues = ["travel", "food", "shopping", "entertainment", "other"])
  val category: String,
)

// Initial prompt to guide the model in identifying and parsing receipts.
val prompt = "Determine if the image is a receipt or expense.
    If it is NOT a receipt or expense, output the text 'NOT_A_RECEIPT'.
    Otherwise, parse the receipt information."

// Constructing the request with the image and initial prompt.
val request = generateContentRequest(ImagePart(bitmap), TextPart(prompt)) 
// Requesting structured output as a ParsedReceipt object.
val requestWithStructuredOutput = generateTypedContentRequest(request, ParsedReceipt::class)

// Configuration for the Gemini Nano 4 E4B preview model, prioritizing reasoning power.
val previewFullConfig = generationConfig 
    modelConfig = modelConfig 
        releaseStage = ModelReleaseStage.PREVIEW
        preference = ModelPreference.FULL // Prioritizing reasoning power over speed.
    


// Obtaining a client for the Gemini Nano 4 preview model.
val geminiNano4BPreviewModel = Generation.getClient(previewFullConfig)
// Generating content and receiving the parsed receipt data.
val response = geminiNano4BPreviewModel.generateContent(requestWithStructuredOutput)
val parsedReceipt: ParsedReceipt? = response.candidates.firstOrNull()?.response

This approach not only ensures data privacy but also significantly simplifies the development workflow by providing structured data directly from the AI model, eliminating the need for complex post-processing logic.

Build intelligent Android apps: On-device inference

Multimodal Input: Seamless Voice Notes with On-Device Transcription

The final on-device intelligent feature introduced in Jetpacker addresses the need for users to easily record audio memos during their travels. This fully on-device voice notes feature utilizes ML Kit’s Speech Recognition API to automatically transcribe spoken words into text. With the transcribed text, the app then leverages ML Kit’s Prompt API to identify which specific trip activity the voice note is associated with, allowing users to effortlessly recap their journey as they review their itinerary.

The ML Kit GenAI Speech Recognition API offers two distinct modes for on-device transcription. The Basic mode, available on most Android devices with API level 31 and higher, employs a traditional on-device speech recognition model. The Advanced mode, however, utilizes Gemini Nano to provide broader language coverage and enhanced transcription quality, currently supported on Pixel 10 devices.

The implementation elegantly combines the Speech Recognition API with the ML Kit GenAI Prompt API:

// Dependencies for ML Kit's GenAI Prompt and Speech Recognition APIs.
// implementation("com.google.mlkit:genai-prompt:1.0.0-beta3")
// implementation("com.google.mlkit:genai-speech-recognition:1.0.0-alpha1")

// Placeholder for trip event data.
val tripEvents = listOf("Visit the Eiffel Tower", "Explore the Louvre Museum", "Dinner in Montmartre")

// Setting up speech recognition options, prioritizing advanced mode and US locale.
val speechRecognizerOptions =
    speechRecognizerOptions 
        locale = Locale.US
        preferredMode = SpeechRecognizerOptions.Mode.MODE_ADVANCED
    
// Obtaining a client for the speech recognizer.
val speechRecognizer: SpeechRecognizer = SpeechRecognition.getClient(speechRecognizerOptions)

// Coroutine function to handle voice note transcription and processing.
suspend fun transcribeVoiceNote(recognizer: SpeechRecognizer) 
    // Variables to store partial and final transcription results.
    var partialTextResponse = ""
    var transcription = ""

    // Creating a speech recognition request from the microphone.
    val request: SpeechRecognizerRequest
        = speechRecognizerRequest  audioSource = AudioSource.fromMic() 

    // Starting the recognition process and collecting responses.
    recognizer.startRecognition(request).collect  response ->
        when (response) 
            is SpeechRecognizerResponse.PartialTextResponse -> 
                // Update UI with partial transcription as the user speaks.
                partialTextResponse = response.text
            
            is SpeechRecognizerResponse.FinalTextResponse -> 
                // Final transcription received.
                transcription = response.text
                // Process the transcribed voice note and categorize it.
                processAndCategorizeVoiceNote(transcription, tripEvents)
            
        
    


// Function to process the transcribed voice note and link it to trip events.
fun processAndCategorizeVoiceNote(transcribedVoiceNote: String, events: List<Event>) 
    // Prompt to clean up transcription and match it with trip events.
    val prompt = "Given the voice note $transcribedVoiceNote
     and the following events for this trip: $events, rewrite this transcription
     to remove filler words. Then, identify which events from the
     list this rewritten transcription matches to."

     // Utilizing ML Kit's Prompt API to process the voice note and tag it with relevant trip activities.
     Generation.getClient().generateContent(prompt)

This integration allows for a seamless user experience, where spoken notes are not only transcribed accurately but also contextually linked to specific trip activities, enhancing the overall organization and recall of travel memories.

Conclusion: A New Era of On-Device Intelligence

Build intelligent Android apps: On-device inference

The advancements demonstrated in the Jetpacker application underscore a significant shift in Android development, empowering developers to build sophisticated, on-device intelligent features. By leveraging ML Kit’s GenAI APIs in conjunction with Gemini Nano, developers can create personalized and agentic experiences that prioritize user privacy, offer reduced latency, and function effectively offline, all without incurring additional cloud infrastructure costs.

The "Build intelligent Android apps" series continues to explore this transformative landscape. Following this deep dive into on-device intelligence, subsequent posts will venture into hybrid and cloud reasoning with Firebase AI Logic, system integration with AppFunctions, and the development of in-app agentic workflows, promising a comprehensive guide to building the next generation of intelligent Android applications.

The full source code for the Jetpacker application is available on GitHub, offering developers a practical resource to explore and implement these cutting-edge AI capabilities. The accompanying video, "Build Intelligent Android apps with Google’s AI," provides further insights into integrating on-device models, cloud-powered reasoning, and agentic frameworks into your own applications.

Learn More:

This article is part of a series exploring the development of intelligent Android applications:

  • Part 1: Introduction of the app and a high-level overview.
  • Part 2 (This post): On-device intelligence. A deep dive into ML Kit’s GenAI APIs and Gemini Nano for building privacy-first features like itinerary summarization, receipt parsing, and local audio processing.
  • Part 3: Hybrid and cloud reasoning. Exploring how to use Firebase AI Logic to ground LLM answers in real-world data like Google Maps and web context.
  • Part 4: System integration. Integrating with the Android intelligence system using AppFunctions.
  • Part 5 (Coming soon): In-app agentic workflows. Extending the app with an end-to-end booking assistant powered by A2UI and ADK.

For further exploration into Android Development, follow Android Developers on YouTube or LinkedIn.

Build intelligent Android apps: On-device inference

Copyright 2026 Google LLC. SPDX-License-Identifier: Apache-2.0

]]>
https://codeguilds.com/build-intelligent-android-apps-with-on-device-gemini-nano-and-ml-kit/feed/ 0
Build Intelligent Android Apps: Leveraging Gemini Nano for On-Device Personalization and Agentic Experiences https://codeguilds.com/build-intelligent-android-apps-leveraging-gemini-nano-for-on-device-personalization-and-agentic-experiences/ https://codeguilds.com/build-intelligent-android-apps-leveraging-gemini-nano-for-on-device-personalization-and-agentic-experiences/#respond Tue, 21 Jul 2026 22:27:33 +0000 https://codeguilds.com/build-intelligent-android-apps-leveraging-gemini-nano-for-on-device-personalization-and-agentic-experiences/ Google is ushering in a new era of intelligent Android applications, empowering developers to create personalized, sophisticated, and agentic user experiences directly on mobile devices. This transformative approach, detailed in an ongoing blog series, centers on the integration of advanced AI models, most notably Gemini Nano, through Google’s ML Kit. The Jetpacker demo application serves as a tangible example, showcasing how developers can elevate a basic app into a dynamic, context-aware tool. This second installment delves into the practical application of Gemini Nano via ML Kit’s Prompt API, illuminating the path to building intelligent, on-device features that prioritize user privacy and enhance functionality.

The core tenet of this advancement is the ability to process prompts and data locally on a user’s device, eliminating the necessity of sending sensitive information to remote servers. This paradigm shift offers a multitude of benefits, including enhanced data privacy and security, reduced latency for real-time interactions, improved offline functionality, and a significant reduction in cloud infrastructure costs for developers. In the context of the Jetpacker app, these advantages translate into three key user experience enhancements: intelligent summarization of trip itineraries, streamlined expense management, and efficient voice note capture.

On-Device Intelligence for Enhanced Travel Planning

The itinerary screen within the Jetpacker app, designed to provide a comprehensive overview of travel plans, can often become information-dense and overwhelming. To counteract this, developers can implement an "Get ready for your trip" section. This feature leverages Gemini Nano to process a trip itinerary and generate a concise summary, complete with practical preparation tips and relevant local phrases.

Build intelligent Android apps: On-device inference

This capability is particularly well-suited for on-device processing due to several compelling reasons. Firstly, the sensitive nature of travel plans, which can include personal preferences and destination details, makes local processing a significant privacy advantage. Secondly, the immediate availability of summarization and tips, even in areas with limited connectivity, ensures a seamless user experience. Finally, the computational demands of summarizing text and generating short, actionable advice are well within the capabilities of modern mobile chipsets, making on-device execution efficient.

Google’s Gemini Nano, the company’s most efficient model tailored for mobile devices, forms the backbone of these on-device features. Introduced several years ago, Gemini Nano has already reached over 140 million devices. The latest iteration, Gemini Nano 4, built upon the architectural foundation of the recently released Gemma 4 model, offers further optimizations for battery and performance efficiency. This latest version is crucial for enabling complex AI tasks directly on a smartphone without draining power or causing significant slowdowns.

Developers can harness Gemini Nano 4’s advanced capabilities through ML Kit’s Prompt API. The process involves crafting specific prompts that guide the model’s output. For the itinerary summarization, a prompt can be designed to include the trip itinerary and instruct the model to generate an "overall vibe," "tips on how to prepare," and "common short phrases to learn."

// Add dependency to your app's build.gradle file:
// implementation("com.google.mlkit:genai-prompt:1.0.0-beta3")

// Define the configuration for Gemini Nano 4 E2B preview model
val previewFastConfig = generationConfig 
    modelConfig = modelConfig 
        releaseStage = ModelReleaseStage.PREVIEW
        preference = ModelPreference.FAST // Prioritizes speed for quick responses
    


val geminiNano2BPreviewModel = Generation.getClient(previewFastConfig)

val tripItinerary = "Day 1: Arrive in Paris, check into hotel, Eiffel Tower visit. Day 2: Louvre Museum, Notre Dame Cathedral. Day 3: Montmartre exploration, Seine River cruise."

val getReadyForYourTripSummary = geminiNano2BPreviewModel
 .generateContent("Given this trip itinerary: $tripItinerary,
     generate the following: overall vibe, tips on how to prepare for this
     trip, and common short phrases to learn for the trip.")

The process of refining these prompts is iterative. Tools like the AICore app, which offers a developer preview option, allow developers to download preview models like Gemini Nano 4 and test prompts to observe expected outputs. Through such iterative refinement, the response time for itinerary summarization in Jetpacker was dramatically reduced from approximately 13 seconds to under 2 seconds, demonstrating the power of prompt engineering and on-device optimization. The final code implementation and optimized prompt are available on GitHub for developers to explore.

Build intelligent Android apps: On-device inference

The optimization of prompts is critical for managing the computational resources of on-device models. An overly verbose or complex prompt can lead to longer processing times and potentially less focused outputs. By carefully structuring the prompt and specifying the desired output format, developers can ensure that the AI model delivers concise, relevant, and timely information, significantly enhancing the user’s interaction with the application. This meticulous approach to prompt design is a hallmark of efficient on-device AI development.

Local Processing for Secure Expense Management

The second key feature introduced is a simplified expense manager, designed to alleviate the manual effort involved in tracking receipts and calculating budgets. This feature allows users to capture photos of restaurant bills, with the app then parsing the data and presenting it in an organized expense overview.

The critical aspect of this feature is the handling of potentially sensitive information contained within receipts, such as credit card numbers and addresses. By processing this data entirely on-device, users can maintain confidence that their private financial information is being handled securely, without any transmission to cloud servers. This commitment to local processing directly addresses growing user concerns about data privacy in an increasingly connected world.

Gemini Nano 4’s enhanced multimodal capabilities are particularly beneficial here, especially for tasks like Optical Character Recognition (OCR) and visual data extraction. This makes it an ideal solution for accurately extracting information from receipts.

Build intelligent Android apps: On-device inference

For this use case, the prompt is designed to analyze an image of a receipt and extract specific details: a generated title for the expense, the total amount spent, and the category of the expense. To ensure the model outputs this information in a structured and usable format, developers can leverage ML Kit’s Structured Output API. This API seamlessly converts the model’s output into a predefined Kotlin data object, streamlining the integration process.

// Add dependencies to your app's build.gradle file:
// implementation("com.google.mlkit:genai-prompt:1.0.0-beta3")
// ksp("com.google.mlkit:genai-schema-compiler:1.0.0-alpha1")

@Generable("Information extracted from an expense receipt")
data class ParsedReceipt(
  @Guide("Generated title for the expense less than 6 words. Based on restaurant or activity name.")
  val  String,
  @Guide("Total amount of the expense. Look for values at the bottom and words like total or balance due.")
  val amount: Double,
  @Guide("Type of expense", enumValues = ["travel", "food", "shopping", "entertainment", "other"])
  val category: String,
)

val prompt = "Determine if the image is a receipt or expense.
    If it is NOT a receipt or expense, output the text 'NOT_A_RECEIPT'.
    Otherwise, parse the receipt information."

// Assuming 'bitmap' is a Bitmap object containing the receipt image
val request = generateContentRequest(ImagePart(bitmap), TextPart(prompt)) 
val requestWithStructuredOutput = generateTypedContentRequest(request, ParsedReceipt::class)

// Define the configuration for Gemini Nano 4 E4B preview model
// ModelPreference.FULL prioritizes reasoning power over speed, suitable for complex analysis.
val previewFullConfig = generationConfig 
    modelConfig = modelConfig 
        releaseStage = ModelReleaseStage.PREVIEW
        preference = ModelPreference.FULL
    


val geminiNano4BPreviewModel = Generation.getClient(previewFullConfig)
val response = geminiNano4BPreviewModel.generateContent(requestWithStructuredOutput)
val parsedReceipt: ParsedReceipt? = response.candidates.firstOrNull()?.response

The choice between ModelPreference.FAST and ModelPreference.FULL in ML Kit’s generationConfig is a critical decision for developers. ModelPreference.FAST is ideal for scenarios where low latency is paramount and the AI task is relatively straightforward, such as generating a quick summary. Conversely, ModelPreference.FULL is suited for more complex reasoning and analysis, such as meticulously extracting data from a receipt where accuracy and thoroughness are prioritized over immediate response time. This fine-grained control allows developers to optimize AI integration for specific application needs and device capabilities.

Multimodal Input for Seamless Voice Note Integration

The final intelligent feature integrated into Jetpacker is a fully on-device voice notes functionality. This feature empowers users to record short audio memos during their travels, which are then automatically transcribed into text. Subsequently, ML Kit’s Prompt API is employed to associate these transcribed voice notes with specific trip activities, enabling users to easily recap their experiences as they navigate their trip itinerary.

The ML Kit GenAI Speech Recognition API facilitates on-device audio transcription through two distinct modes. The "Basic mode" utilizes traditional on-device speech recognition models and is compatible with most Android devices running API level 31 and higher. The "Advanced mode," however, leverages Gemini Nano to offer enhanced language coverage and superior transcription quality, currently supported on Pixel 10 devices.

Build intelligent Android apps: On-device inference

This voice note feature elegantly combines the Speech Recognition API with the ML Kit GenAI Prompt API. The process involves:

  1. Speech Recognition: Users record audio via their device’s microphone. The SpeechRecognizer from ML Kit processes this audio in real-time. It can display partial transcriptions as the user speaks and provides a final, complete transcription once the recording is finished.
  2. Transcription Processing: Once the audio is transcribed, the text is processed. This includes cleaning up filler words and ensuring clarity.
  3. Event Association: The cleaned transcription is then fed into the Prompt API along with a list of the trip’s events. The AI model analyzes both the transcribed voice note and the trip events to identify which specific activities the voice note pertains to.
// Add dependencies to your app's build.gradle file:
// implementation("com.google.mlkit:genai-prompt:1.0.0-beta3")
// implementation("com.google.mlkit:genai-speech-recognition:1.0.0-alpha1")

val tripEvents = listOf("Eiffel Tower visit", "Louvre Museum tour", "Seine River cruise") // Example trip events

// Set up speech recognition with advanced mode for better quality
val speechRecognizerOptions =
    speechRecognizerOptions 
        locale = Locale.US
        preferredMode = SpeechRecognizerOptions.Mode.MODE_ADVANCED // Leverages Gemini Nano on supported devices
    
val speechRecognizer: SpeechRecognizer = SpeechRecognition.getClient(speechRecognizerOptions)

suspend fun transcribeVoiceNote(recognizer: SpeechRecognizer) 
    // Display partial text as the user is recording audio
    var partialTextResponse = ""

    // Display the full text once user is finished recording audio
    var transcription = ""

    val request: SpeechRecognizerRequest
        = speechRecognizerRequest  audioSource = AudioSource.fromMic()  // Capture audio from microphone
    recognizer.startRecognition(request).collect  response ->
        when (response) 
            is SpeechRecognizerResponse.PartialTextResponse -> 
                partialTextResponse = response.text
                // Update UI with partial transcription
            
            is SpeechRecognizerResponse.FinalTextResponse -> 
                transcription = response.text
                processAndCategorizeVoiceNote(transcription, tripEvents)
            
        
    


fun processAndCategorizeVoiceNote(transcribedVoiceNote: String, events: List<Event>) 
    val prompt = "Given the voice note '$transcribedVoiceNote'
     and the following events for this trip: $events, rewrite this transcription
     to remove filler words. Then, identify which events from the
     list this rewritten transcription matches to. Format the output as a JSON object with 'cleaned_note' and 'matched_events' keys."

     // Utilize ML Kit's Prompt API to process voice note and tag it with the relevant trip activities
     val response = Generation.getClient().generateContent(prompt)
     // Parse the JSON response to extract cleaned_note and matched_events
     // Update UI to display the voice note associated with relevant trip events

The integration of these on-device intelligent features within the Jetpacker app underscores a significant shift in mobile application development. By leveraging ML Kit’s GenAI APIs and the power of Gemini Nano, developers can create applications that are not only more functional but also more privacy-conscious and cost-effective.

Conclusion and Future Outlook

The successful implementation of itinerary summarization, expense management, and voice note features within the Jetpacker app demonstrates the tangible benefits of on-device AI. These intelligent capabilities, powered by Gemini Nano and ML Kit, provide an enriched user experience without incurring additional cloud infrastructure costs. Developers are encouraged to explore the full source code of Jetpacker on GitHub and delve deeper into the principles of building intelligent Android apps through accompanying video resources.

This ongoing blog series provides a comprehensive roadmap for developers interested in integrating advanced AI into their Android applications. The series covers a spectrum of approaches, from purely on-device inference to hybrid cloud-based reasoning and system integration with agentic frameworks. The progression through these topics highlights Google’s commitment to empowering developers with the tools and knowledge necessary to create the next generation of intelligent, personalized, and agentic mobile experiences.

Build intelligent Android apps: On-device inference

The trend towards on-device AI processing is not merely a technical evolution but a response to growing user demands for privacy, security, and seamless functionality. As AI models become more efficient and mobile hardware more capable, the potential for sophisticated on-device intelligence is virtually limitless. This opens up new avenues for innovation in areas ranging from personalized healthcare and education to advanced productivity tools and immersive entertainment. The future of Android development is undoubtedly intelligent, and Google’s latest advancements are paving the way for a more intuitive and empowering mobile ecosystem.

]]>
https://codeguilds.com/build-intelligent-android-apps-leveraging-gemini-nano-for-on-device-personalization-and-agentic-experiences/feed/ 0