By Shakil Ahmed, Android developer & software engineer
Add an AI Chat to Your Android App with the Gemini API
Build a secure AI chat in your Android app with Firebase AI Logic and Gemini: setup, App Check, model choice, streaming ViewModel, Compose UI and error handling.
Want your app to answer questions, explain things, or chat like a helpful assistant? With the Gemini API Android developers can add a real AI chat in an afternoon, and you do not need to build your own backend. In this guide, I will show you the safe, current way to do it with Kotlin, Jetpack Compose, and Firebase AI Logic.
We will build a small chat screen step by step. You will see how to set up Firebase, pick a model, stream answers word by word, and handle errors like a professional app. If you know basic Compose and ViewModels, you are ready.
Why You Should Not Put a Gemini API Key in Your App
Let's start with the most important rule. Never ship a raw Gemini API key inside your APK.
An APK is like a sealed envelope that anyone can open. Tools like apktool or jadx can read your strings, your BuildConfig fields, and even "hidden" native code in a few minutes. If someone finds your key, they can use it from their own scripts. You pay the bill. Your quota disappears. Your app stops working for real users.
In the past, many tutorials used the old Google AI client SDK (com.google.ai.client.generativeai:generativeai) with a key in local.properties. That SDK is now deprecated, and Google tells developers to migrate to the Firebase AI Logic SDK.
Firebase AI Logic works differently:
- Your app talks to a Firebase proxy, not directly to Gemini with your key.
- The real Gemini key stays on Google's servers.
- Firebase App Check proves the request comes from your genuine, untampered app.
- You can add per-user rate limits so one user cannot drain your quota.
Think of it like a hotel reception. Guests do not get the master key. They show their room card, and the reception decides what they can access.
Warning: Even with Firebase AI Logic, your project is only protected when App Check is enforced. Without it, anyone who copies your
google-services.jsoncould call your AI endpoint. I wrote more about these risks in AI security testing on Android: from findings to fixes.
Step 1: Set Up Firebase AI Logic
Here is the setup, in plain steps:
- Open the Firebase console and create a project (or use an existing one).
- Go to AI Logic in the left menu and click Get started. The guided setup turns on the required APIs.
- Choose your Gemini API provider (more on this below).
- Register your Android app with its package name.
- Download
google-services.jsonand put it in yourapp/folder.
Now add the Gradle plugin and dependencies. In your project-level build.gradle.kts:
plugins {
// Defined in libs.versions.toml with the latest version
// from the Firebase setup guide
alias(libs.plugins.google.gms.google.services) apply false
}
In your app-level build.gradle.kts:
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("com.google.gms.google-services")
}
dependencies {
// Firebase BoM controls the versions of all Firebase libraries
implementation(platform("com.google.firebase:firebase-bom:35.1.0"))
// Firebase AI Logic SDK
implementation("com.google.firebase:firebase-ai")
// App Check (debug provider for development builds)
debugImplementation("com.google.firebase:firebase-appcheck-debug")
// Use Play Integrity for release builds
implementation("com.google.firebase:firebase-appcheck-playintegrity")
// Compose + lifecycle helpers used in this tutorial
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.11.0")
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.11.0")
}
Tip: As of November 2026, the Firebase docs show BoM
35.1.0withfirebase-ai18.1.0. Always check the Firebase AI Logic get-started guide for the latest version before you copy numbers.
Turn On App Check
The guided setup in the console can enforce App Check for AI Logic automatically. In your app, install a provider early, for example in your Application class:
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
Firebase.initialize(this)
Firebase.appCheck.installAppCheckProviderFactory(
if (BuildConfig.DEBUG) DebugAppCheckProviderFactory.getInstance()
else PlayIntegrityAppCheckProviderFactory.getInstance()
)
}
}
Let's understand it:
- In debug builds, the debug provider prints a token in Logcat. You register that token in the Firebase console so your emulator can call the API.
- In release builds, Play Integrity checks that the request comes from your real app installed from Google Play.
- Never ship the debug provider or debug token in production.
Step 2: Gemini Developer API vs Agent Platform
Firebase AI Logic supports two providers. Note that Vertex AI has a new name: the Agent Platform Gemini API (formerly Vertex AI).
| Feature | Gemini Developer API | Agent Platform Gemini API |
|---|---|---|
| Best for | Beginners, side projects, startups | Teams already on Google Cloud |
| Free tier | Yes, no payment method needed | Paid (the $300 Google Cloud trial credit can be used) |
| Billing | Optional paid tier (Blaze) | Uses Google Cloud billing |
| Location control | No | Yes, choose a region |
| Kotlin backend | GenerativeBackend.googleAI() | GenerativeBackend.agentPlatform() |
Google's Android docs say most developers who are just starting should begin with the Gemini Developer API. Good news: switching later is a one-line change in the constructor.
Step 3: Choose the Right Gemini Model
As of November 2026, the Firebase AI Logic model list features gemini-3.8-flash as the main Flash model. It is fast, capable, and usable without billing on the Developer API. For very high-volume, cost-sensitive tasks, gemini-3.5-flash-lite is the lighter option. Older models like gemini-2.5-flash are being retired or routed to newer models.
Models change often. A model that is "latest" today can be shut down next year. So do not hardcode the name in ten places. Keep it in one constant, or better, load it with Firebase Remote Config so you can switch models without a new app release.
object AiConfig {
// As of November 2026. Check firebase.google.com/docs/ai-logic/models
const val MODEL_NAME = "gemini-3.8-flash"
}
Step 4: Build the ChatViewModel with Streaming
Now the fun part. We want a chat that remembers previous messages and shows the answer while it is being generated, like ChatGPT or the Gemini app.
Firebase AI Logic gives us two helpful functions:
model.startChat()creates a chat session that keeps the history for you.chat.sendMessageStream(text)returns a KotlinFlowof chunks. Each chunk has atextproperty.
If Kotlin Flow is new for you, read my Kotlin coroutines guide first.
First, our UI models:
data class ChatMessage(
val id: Long,
val text: String,
val isFromUser: Boolean
)
data class ChatUiState(
val messages: List<ChatMessage> = emptyList(),
val isLoading: Boolean = false,
val errorMessage: String? = null
)
Now the ViewModel:
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.firebase.Firebase
import com.google.firebase.ai.ai
import com.google.firebase.ai.type.FirebaseAIException
import com.google.firebase.ai.type.GenerativeBackend
import com.google.firebase.ai.type.PromptBlockedException
import com.google.firebase.ai.type.QuotaExceededException
import com.google.firebase.ai.type.ResponseStoppedException
import com.google.firebase.ai.type.content
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
class ChatViewModel : ViewModel() {
private val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel(
modelName = AiConfig.MODEL_NAME,
systemInstruction = content {
text(
"You are a friendly assistant inside a cooking app. " +
"Answer in simple English, in less than 150 words. " +
"If a question is not about food or cooking, politely say you can only help with cooking."
)
}
)
// The chat object keeps the conversation history for us
private val chat = model.startChat()
private val _uiState = MutableStateFlow(ChatUiState())
val uiState: StateFlow<ChatUiState> = _uiState.asStateFlow()
private var nextId = 0L
fun sendMessage(input: String) {
val prompt = input.trim()
if (prompt.isEmpty() || _uiState.value.isLoading) return
val userMessage = ChatMessage(nextId++, prompt, isFromUser = true)
val replyId = nextId++
val emptyReply = ChatMessage(replyId, "", isFromUser = false)
_uiState.update {
it.copy(
messages = it.messages + userMessage + emptyReply,
isLoading = true,
errorMessage = null
)
}
viewModelScope.launch {
try {
chat.sendMessageStream(prompt).collect { chunk ->
val piece = chunk.text ?: return@collect
appendToMessage(replyId, piece)
}
} catch (e: CancellationException) {
throw e // never swallow coroutine cancellation
} catch (e: QuotaExceededException) {
showError(replyId, "Too many requests right now. Please try again in a minute.")
} catch (e: PromptBlockedException) {
showError(replyId, "Sorry, I can't help with that message.")
} catch (e: ResponseStoppedException) {
showError(replyId, "The answer was stopped early. Please try again.")
} catch (e: FirebaseAIException) {
showError(replyId, "Something went wrong. Please check your connection.")
} catch (e: Exception) {
showError(replyId, "Unexpected error. Please try again.")
} finally {
_uiState.update { it.copy(isLoading = false) }
}
}
}
fun dismissError() = _uiState.update { it.copy(errorMessage = null) }
private fun appendToMessage(id: Long, piece: String) {
_uiState.update { state ->
state.copy(messages = state.messages.map { msg ->
if (msg.id == id) msg.copy(text = msg.text + piece) else msg
})
}
}
private fun showError(replyId: Long, message: String) {
_uiState.update { state ->
state.copy(
// Remove the reply bubble only if nothing was streamed into it
messages = state.messages.filterNot { it.id == replyId && it.text.isEmpty() },
errorMessage = message
)
}
}
}
Let's understand it:
Firebase.ai(backend = GenerativeBackend.googleAI())selects the Gemini Developer API. Change it toGenerativeBackend.agentPlatform()to use the Agent Platform.systemInstructionis like a job description for the model. The user never sees it, but it shapes every answer.startChat()is called once. The chat object adds every user message and model reply to its history, so the model remembers the conversation.- We add an empty reply bubble first. Then each streamed chunk is appended to it. This creates the "typing" effect.
- We catch specific exceptions first (quota, blocked prompt, stopped response), then the parent
FirebaseAIException. - We rethrow
CancellationExceptionso the coroutine stops cleanly when the ViewModel is cleared. isLoadingblocks a second message while the first answer is still streaming.
If you want the full answer in one piece, use chat.sendMessage(prompt) instead. It is a suspend function that returns a response with a text property. Streaming feels faster for users, so I prefer it for chat.
Tip: Want to understand why the model "remembers" and why long chats get expensive? Every message in the history is sent again as tokens. My upcoming post on how LLMs work: tokens, context and temperature explains this in detail.
Step 5: Build the Compose Chat UI
Now we show the messages. We need three parts: a list of bubbles, a text field with a send button, and a loading or error state. If ViewModels in Compose are new to you, read Jetpack Compose ViewModel for beginners.
@Composable
fun ChatScreen(viewModel: ChatViewModel = viewModel()) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
var input by rememberSaveable { mutableStateOf("") }
val listState = rememberLazyListState()
// Scroll to the newest message when the list grows or text streams in
val lastText = state.messages.lastOrNull()?.text
LaunchedEffect(state.messages.size, lastText) {
if (state.messages.isNotEmpty()) {
listState.animateScrollToItem(state.messages.lastIndex)
}
}
Scaffold { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.imePadding()
) {
LazyColumn(
state = listState,
modifier = Modifier.weight(1f).fillMaxWidth(),
contentPadding = PaddingValues(12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(state.messages, key = { it.id }) { message ->
MessageBubble(message)
}
}
state.errorMessage?.let { error ->
Text(
text = error,
color = MaterialTheme.colorScheme.error,
modifier = Modifier
.fillMaxWidth()
.clickable { viewModel.dismissError() }
.padding(horizontal = 16.dp, vertical = 4.dp)
)
}
Row(
modifier = Modifier.fillMaxWidth().padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
OutlinedTextField(
value = input,
onValueChange = { input = it },
modifier = Modifier.weight(1f),
placeholder = { Text("Ask about any recipe...") },
maxLines = 4
)
Spacer(Modifier.width(8.dp))
if (state.isLoading) {
CircularProgressIndicator(modifier = Modifier.size(32.dp))
} else {
IconButton(
onClick = {
viewModel.sendMessage(input)
input = ""
},
enabled = input.isNotBlank()
) {
Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send")
}
}
}
}
}
}
@Composable
fun MessageBubble(message: ChatMessage) {
val isUser = message.isFromUser
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = if (isUser) Alignment.CenterEnd else Alignment.CenterStart
) {
Surface(
shape = RoundedCornerShape(16.dp),
color = if (isUser) MaterialTheme.colorScheme.primaryContainer
else MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.widthIn(max = 300.dp)
) {
Text(
text = message.text.ifEmpty { "Thinking..." },
modifier = Modifier.padding(12.dp),
style = MaterialTheme.typography.bodyLarge
)
}
}
}
Let's understand it:
collectAsStateWithLifecycle()collects theStateFlowonly while the screen is visible.- The
LaunchedEffectkeys include the last message text, so the list keeps scrolling while the answer streams. items(..., key = { it.id })gives each bubble a stable key, so Compose updates only the changed bubble.- The empty reply bubble shows "Thinking..." until the first chunk arrives. This is a simple, friendly loading state.
imePadding()keeps the text field above the keyboard.
For more patterns like retry buttons and empty screens, see loading and error states in Jetpack Compose. And if you want to separate this into repository and use-case layers, my post on clean architecture for Android shows how.
Writing Good System Instructions
The system instruction is your strongest tool for controlling the AI. A good one has four parts:
- Role: "You are a cooking assistant."
- Style: "Use simple English and short paragraphs."
- Limits: "Only answer questions about cooking."
- Format: "Use a numbered list for recipe steps."
Keep it short and clear. Long, confusing instructions give confusing results. For more techniques, read my upcoming guide on prompt engineering for developers.
Tip: Your system instruction lives inside your APK, so a curious user can read it. Do not put secrets in it. Firebase AI Logic also supports server prompt templates, which keep the prompt on the server and send only a template ID from the app.
Handling Errors, Quotas, and Costs
Real users will hit errors. Plan for them from day one.
| Exception | What it means | What to show |
|---|---|---|
QuotaExceededException | Too many requests (HTTP 429) | "Please try again in a minute." |
PromptBlockedException | The prompt was blocked for safety | "I can't help with that." |
ResponseStoppedException | The answer stopped early | "Please try again." |
ServerException | A problem on the server side | Retry with a short delay |
FirebaseAIException | Parent class for SDK errors | A general error message |
About quotas and costs (as of November 2026):
- The Gemini Developer API has a free tier that does not need a payment method. Your Firebase project stays on the no-cost Spark plan.
- The free tier gives limited access to certain models. Some models, especially preview and media-generating ones, may need billing.
- Firebase AI Logic has a per-user rate limit, 100 requests per minute by default. You can lower it in the console to fit your app.
- When you move to production, set budget alerts so you do not get a surprise bill.
Prices and limits change often, so always check the official pricing page before launch.
Safety and Responsible AI
Gemini has built-in safety filters. If a prompt or answer is harmful, the SDK may block it, and you get an exception or an empty response. Your job is to handle this gracefully, not crash.
A few more rules I follow:
- Tell users they are talking to AI. A small label like "AI answers may be wrong" builds trust.
- Do not send private data you do not need. Avoid passwords, ID numbers, or health data in prompts.
- Validate AI output before acting on it. If the AI suggests an action (delete, pay, send), ask the user to confirm.
- Expect prompt injection. Users may type "ignore your instructions". Your system instruction helps, but never give the model power you cannot afford to lose.
Want a voice interface on top of this chat? My post on designing voice AI apps beyond the microphone button covers the UX side.
What About On-Device AI?
Cloud models are powerful, but they need internet and cost money per request. For some tasks, like summarizing a note or fixing grammar, a small model on the phone is enough. Read my companion guide, On-Device AI on Android: Gemini Nano and ML Kit GenAI APIs, to learn when to use each and how to fall back from one to the other.
Frequently Asked Questions
Is the Gemini API free to use in Android apps? Yes, the Gemini Developer API has a free tier with no payment method required, as of November 2026. It has rate limits and limited model access. For larger apps, you can upgrade to the paid tier.
Can I still use the Google AI client SDK for Android?
It is deprecated and no longer recommended. Google asks developers to migrate to the Firebase AI Logic SDK (com.google.firebase:firebase-ai), which supports App Check and both API providers.
Which Gemini model should I use for a chat app?
As of November 2026, gemini-3.8-flash is the featured Flash model in the Firebase AI Logic docs and is a good default for chat. Load the model name from Remote Config so you can switch when new models arrive.
Do I need my own backend server to use Gemini?
No. Firebase AI Logic acts as the secure proxy for you. You only need a Firebase project, google-services.json, and App Check enforced for production.
Key Takeaways
- Never put a raw Gemini API key in your APK. Use Firebase AI Logic with App Check enforced.
- The old Google AI client SDK for Android is deprecated. Use
com.google.firebase:firebase-aiwith the Firebase BoM. - Start with the Gemini Developer API backend; switch to
agentPlatform()later if you need Google Cloud features. - As of November 2026,
gemini-3.8-flashis the featured Flash model. Keep the model name configurable. - Use
startChat()once andsendMessageStream()with Kotlin Flow for a smooth, streaming chat. - Handle quota, blocked prompts, and network errors with clear messages, and follow simple safety rules.
Related articles
Run AI directly on the phone with Gemini Nano and ML Kit GenAI APIs: privacy, offline use, device support, a Compose summarizer, cloud fallback and limits.
Pick a photo, read its text on-device with ML Kit Text Recognition v2, and show blocks and lines in Jetpack Compose with a copy button.
Use SavedStateHandle to restore a Compose search query, reload its results, and test the difference between rotation and process recreation.
Create your first Android project, understand every line of MainActivity.kt in plain English, and run your Hello World app on an emulator or your phone.