惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

K
Kaspersky official blog
Engineering at Meta
Engineering at Meta
D
DataBreaches.Net
Stack Overflow Blog
Stack Overflow Blog
Microsoft Security Blog
Microsoft Security Blog
Y
Y Combinator Blog
B
Blog RSS Feed
GbyAI
GbyAI
P
Proofpoint News Feed
aimingoo的专栏
aimingoo的专栏
MyScale Blog
MyScale Blog
D
Docker
阮一峰的网络日志
阮一峰的网络日志
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recorded Future
Recorded Future
美团技术团队
The Register - Security
The Register - Security
V
Visual Studio Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Tailwind CSS Blog
爱范儿
爱范儿
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
The Blog of Author Tim Ferriss
博客园 - 司徒正美
量子位
B
Blog
F
Fortinet All Blogs
Martin Fowler
Martin Fowler
博客园 - 【当耐特】
MongoDB | Blog
MongoDB | Blog
A
About on SuperTechFans
I
InfoQ
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
有赞技术团队
有赞技术团队
雷峰网
雷峰网
大猫的无限游戏
大猫的无限游戏
J
Java Code Geeks
L
LangChain Blog
Latest news
Latest news
S
SegmentFault 最新的问题
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Blog — PlanetScale
Blog — PlanetScale
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cisco Talos Blog
Cisco Talos Blog
F
Full Disclosure
C
Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
W
WeLiveSecurity
T
Tenable Blog
T
Tor Project blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Beyond the Prompt: Mastering Context Windows and Stateless Inference in Android GenAI
Programming · 2026-04-27 · via DEV Community

The era of on-device Generative AI has arrived, and for Android developers, it brings a paradigm shift as significant as the transition from imperative UI to Jetpack Compose. When Google announced Gemini Nano and the AICore system service, the promise was clear: powerful, private, and low-latency AI running directly on the silicon in our pockets. However, as developers begin to move beyond simple "Hello World" prompts, they encounter a formidable technical wall: the architecture of memory.

If you have ever wondered why your on-device model suddenly "forgets" the beginning of a conversation, or why a long prompt causes your app to lag or crash with an OutOfMemoryError, you are dealing with the dual challenges of Context Windows and Stateless Inference. Understanding these concepts isn't just academic; it is the difference between a glitchy prototype and a production-ready AI application.

The Architecture of Memory: Understanding the Context Window

At the heart of every Large Language Model (LLM) lies a fundamental tension between computational constraints—RAM, thermal throttling, and battery life—and cognitive capacity. Unlike a traditional relational database where you can query any row regardless of the table size, an LLM like Gemini Nano operates within a strict Context Window.

What is a Context Window?

The context window is the maximum number of tokens (words, characters, or sub-words) that the model can "see" and process at any single moment. Imagine reading a book through a narrow slit in a piece of cardboard; you can only see a few sentences at a time. To see the next sentence, you must slide the cardboard down, losing sight of the first sentence.

If a model has a context window of 4,096 tokens and your conversation reaches 4,097 tokens, the model must "forget" the first token to make room for the new one. In the world of on-device AI, this window is significantly smaller than its cloud-based counterparts (like Gemini 1.5 Pro) because of the hardware it inhabits.

The Quadratic Cost of "Paying Attention"

You might wonder: "Why not just give the model an infinite context window?" The answer lies in the Transformer architecture and its Self-Attention mechanism.

In a standard implementation, the computational cost of attention grows quadratically ($O(n^2)$) relative to the sequence length. This means if you double the number of tokens in your prompt, you don't just double the memory requirement—you quadruple it. On a mobile device, where memory is a precious, shared resource between the CPU, GPU, and NPU, an unbounded context window would lead to immediate system-wide instability.

The Android Analogy: SavedStateHandle

For Android developers, the best way to visualize the context window is to think of it like a Fragment's SavedStateHandle or a Bundle. Just as you cannot store a 100MB bitmap inside a Bundle because the system will throw a TransactionTooLargeException, you cannot push an entire library of data into an LLM's context window. You must be surgical. You must selectively persist only the most critical state, pruning the unnecessary data to keep the "bundle" (the prompt) within the system's physical limits.

The Statelessness Paradox: Why AI Has No Memory

One of the most counter-intuitive aspects of working with LLMs—especially via Android’s AICore or the MediaPipe LLM Inference API—is that LLMs are inherently stateless.

When you send a prompt to Gemini Nano, the model does not "remember" who you are, what time it is, or what you said ten seconds ago. Every single request is a "cold boot." To create the illusion of a flowing, continuous conversation, the developer must implement State Management manually.

The Stateless Loop in Action

To maintain a conversation, you have to pass the entire history back to the model with every new message.

  1. User: "What is Kotlin?" -> Prompt: "What is Kotlin?"
  2. AI: "Kotlin is a modern language..."
  3. User: "Why is it better than Java?" -> Prompt: "User: What is Kotlin? AI: Kotlin is a modern language... User: Why is it better than Java?"

In this flow, the "memory" doesn't live in the AI; it lives in your ViewModel or your database. The responsibility of maintaining context has shifted from the model to the client-side application logic.

Optimizing the "Re-read" with KV Caching

If we are forced to send the entire conversation history every time, doesn't the model have to re-process everything from scratch? If the history is 2,000 tokens long, re-calculating the mathematical "hidden states" for those tokens every time the user hits "send" would result in a massive "Time to First Token" (TTFT) latency.

This is where the KV (Key-Value) Cache comes in. The KV Cache stores the intermediate mathematical representations of previous tokens. Instead of re-calculating the entire prompt, the model calculates the representation for the new tokens and retrieves the previous ones from the cache.

The Android Analogy: Room and Paging 3

Think of the KV Cache as a Room database's InMemory cache or how the Paging 3 library maintains a snapshot of loaded data. Rather than re-fetching the entire dataset from the disk on every scroll, the system keeps the "hot" data in memory for immediate access. On Android, AICore manages this cache to ensure that your chat app feels snappy even as the conversation grows.

Why AICore? The Strategic Shift to System-Level AI

Google’s decision to move Gemini Nano into AICore—a system-level service—rather than providing it as a standard .aar library, is a masterclass in mobile architecture. It solves three critical problems:

  1. Resource Orchestration: LLMs are memory hogs. If five different apps each loaded their own 2GB model into RAM, the Android Low Memory Killer (LMK) would be working overtime, killing background processes and ruining the user experience. AICore acts as a singleton provider, managing a single instance of the model that multiple apps can share.
  2. Model Versioning: AI evolves at a breakneck pace. By housing the model in AICore, Google can update model weights via Google Play System Updates without requiring developers to push a new APK.
  3. Hardware Abstraction: Much like CameraX abstracts the nightmare of different camera sensors, AICore abstracts the NPU/GPU acceleration. Whether your app is running on a Tensor G3 or a Qualcomm Snapdragon, you use the same API, and AICore decides how to optimize the execution.

Implementing the Stateless Chat: A Technical Blueprint

To turn these theoretical concepts into a working Android application, we need to leverage modern Kotlin features like Coroutines, Flow, and Hilt. Below is a production-ready approach to managing a stateless LLM using the MediaPipe LLM Inference API.

The Repository: Managing the Model Lifecycle

The repository should be a singleton to prevent the multi-gigabyte model from being reloaded into RAM multiple times.

@Singleton
class ChatRepository @Inject constructor(
    @ApplicationContext private val context: Context
) {
    private var llmInference: LlmInference? = null

    init {
        val options = LlmInference.LlmInferenceOptions.builder()
            .setModelPath("/data/local/tmp/gemini_nano.bin") 
            .setMaxTokens(1024) 
            .setTemperature(0.7f)
            .build()

        llmInference = LlmInference.createFromOptions(context, options)
    }

    suspend fun generateResponse(fullContext: String): String = withContext(Dispatchers.Default) {
        try {
            // Inference is CPU/GPU intensive; always use Dispatchers.Default
            llmInference?.generateResponse(fullContext) ?: "Model Error"
        } catch (e: Exception) {
            "Inference failed: ${e.localizedMessage}"
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

The ViewModel: The "Brain" of the Stateless Model

The ViewModel is where the "illusion of memory" is created. It transforms a list of messages into a single formatted string that the model can understand.

@HiltViewModel
class ChatViewModel @Inject constructor(
    private val repository: ChatRepository
) : ViewModel() {

    private val _messages = MutableStateFlow<List<ChatMessage>>(emptyList())
    val messages = _messages.asStateFlow()

    fun sendMessage(userText: String) {
        viewModelScope.launch {
            val userMsg = ChatMessage(Role.USER, userText)
            _messages.value = _messages.value + userMsg

            // Construct the stateless prompt from history
            val prompt = buildStatelessPrompt(_messages.value)

            val aiResponse = repository.generateResponse(prompt)
            _messages.value = _messages.value + ChatMessage(Role.AI, aiResponse)
        }
    }

    private fun buildStatelessPrompt(history: List<ChatMessage>): String {
        return history.joinToString(separator = "\n") { msg ->
            val prefix = if (msg.role == Role.USER) "User: " else "AI: "
            "$prefix${msg.text}"
        } + "\nAI:" // The "completion trigger"
    }
}

Enter fullscreen mode Exit fullscreen mode

The "Sliding Window" Strategy: Preventing Context Overflow

As a conversation continues, the buildStatelessPrompt function will eventually generate a string that exceeds the model's token limit. If you don't handle this, your app will crash or the model will produce gibberish.

The solution is a Sliding Window. This involves pruning the conversation history to ensure it fits within the token budget while preserving the most important information: the System Instruction (the "who am I" for the AI) and the Most Recent Messages.

Implementing a Token-Aware Buffer

In a production environment, you should calculate tokens precisely. However, a reliable heuristic is that 1 token is roughly 4 characters in English.

class ContextWindowManager {
    private val MAX_TOKEN_LIMIT = 2048 
    private val SYSTEM_PROMPT_RESERVE = 256 

    fun optimizeContext(
        systemPrompt: String, 
        history: List<ChatMessage>, 
        newQuery: String
    ): String {
        val availableTokens = MAX_TOKEN_LIMIT - SYSTEM_PROMPT_RESERVE
        var currentTokens = 0
        val optimizedHistory = mutableListOf<ChatMessage>()

        // Prioritize the most recent messages by iterating backwards
        for (msg in history.reversed()) {
            val estimatedTokens = msg.text.length / 4
            if (currentTokens + estimatedTokens <= availableTokens) {
                optimizedHistory.add(0, msg)
                currentTokens += estimatedTokens
            } else {
                break 
            }
        }

        return buildString {
            append("System: $systemPrompt\n\n")
            optimizedHistory.forEach { append("${it.role}: ${it.content}\n") }
            append("User: $newQuery\nAI: ")
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Mapping AI Concepts to the Android Ecosystem

To summarize the transition into AI development, it helps to map these new concepts to the tools we already use every day:

AI Concept Android/Kotlin Equivalent Purpose
Context Window SavedStateHandle Managing strict memory limits for state.
Statelessness ViewModel State Management Manually maintaining history between calls.
KV Cache LruCache / Room Speeding up access to frequently used data.
AICore CameraX / Health Connect System-level hardware abstraction and RAM orchestration.
Inference Stream Kotlin Flow Handling asynchronous, token-by-token UI updates.

Conclusion: The New Responsibility of the Android Developer

Building with on-device GenAI is a balancing act. You are no longer just a UI developer; you are a resource manager. By understanding that LLMs are stateless and that context windows are finite, you can build applications that feel intelligent without sacrificing the stability of the Android OS.

The future of mobile apps isn't just about calling an API in the cloud; it's about orchestrating intelligence locally, respecting the user's privacy, and managing the delicate dance of tokens and tensors directly on the device.

Let's Discuss

  1. How do you plan to handle "Context Pruning" in your apps? Would you prefer a simple sliding window, or a more complex strategy like summarizing old messages to save tokens?
  2. With AICore handling model orchestration, do you think we will see a shift toward "AI-first" Android apps that function entirely offline?

If you found this guide helpful, consider sharing it with your fellow Android developers. Let's build the next generation of intelligent apps together!

The concepts and code demonstrated here are drawn directly from the comprehensive roadmap laid out in the ebook
On-Device GenAI with Android Kotlin: Mastering Gemini Nano, AICore, and local LLM deployment using MediaPipe and Custom TFLite models. You can find it here: Leanpub.com or Amazon.
Check also all the other programming & AI ebooks with python, typescript, c#, swift, kotlin: Leanpub.com or Amazon.