DEV Community

goldenlord128-jensy
goldenlord128-jensy

Posted on Edited on

How I Integrated Google Gemini into a Jetpack Compose Android App (With Real Kotlin Patterns)

Integrating Google Gemini into an Android app sounds simple… until you actually try to do it properly in a real Jetpack Compose project.

I recently spent a good amount of time building a clean, production-ready Gemini integration in Kotlin. Here’s what I learned and the patterns that actually worked.

1 . Setting up the Gemini API the right way
First, get your API key from Google AI Studio.

Then add the official dependency:

kotlin
// build.gradle.kts
implementation("com.google.ai.client.generativeai:generativeai:0.9.0") // check for latest

II . Basic text generation (the clean way)
Here’s a simple but solid repository pattern I ended up using:

kotlin
class GeminiRepository(private val apiKey: String) {
private val generativeModel = GenerativeModel(
modelName = "gemini-1.5-flash", // or gemini-1.5-pro
apiKey = apiKey
)

suspend fun generateText(prompt: String): String {
    return try {
        val response = generativeModel.generateContent(prompt)
        response.text ?: "No response"
    } catch (e: Exception) {
        "Error: ${e.message}"
    }
}
Enter fullscreen mode Exit fullscreen mode

}

III . Important things most tutorials skip
Always handle rate limits and network errors properly
Use gemini-1.5-flash for most mobile use cases (faster + cheaper)
Never hardcode the API key (use BuildConfig or local.properties)
Streaming responses feel much better in chat-style UIs
Multimodal (image + text) needs extra care with Bitmap handling

IV . Jetpack Compose UI tip
For a chat-like experience, I recommend using a simple LazyColumn + TextField combination and collecting the response with a ViewModel + StateFlow.

Final Thoughts
Getting a basic Gemini call working is easy.
Making it clean, reusable, and production-ready takes more time than expected (error handling, prompt engineering, Compose state management, etc.).

I ended up packaging all the battle-tested Kotlin code, good system prompts, and Compose examples I used into a small pack so I don’t have to rewrite them again.

You can check it out here if you’re interested:
→ Android Dev's Gemini API Integration & Prompt Pack

Would love to hear how others are using Gemini in their Android apps. Drop your experience or questions below!

Top comments (0)