Gemini 2.0 APIs in Android App
In this video it shows the code to integrate the Gemini 2.0 APIs in your Android App.
Prompts used in this demo:
Hello, how are you?
Could you write a story about cats and dogs?
Write a poem about mango tree.
For API Key, visit Google AI studio: https://aistudio.google.com/prompts/new_chat
I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com
Details:
Source code:
package com.programmerworld.gemini20modelinandroid;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.ai.client.generativeai.GenerativeModel;
import com.google.ai.client.generativeai.type.GenerateContentResponse;
import com.google.ai.client.generativeai.type.Content;
import com.google.ai.client.generativeai.type.TextPart;
import kotlin.coroutines.Continuation;
import kotlin.coroutines.CoroutineContext;
import kotlin.coroutines.EmptyCoroutineContext;
public class MainActivity extends AppCompatActivity {
private EditText etPrompt;
private TextView tvResponse;
private Button btnGenerate;
private static final String MODEL_NAME = "gemini-2.0-flash"; // Use latest stable model
private static final String API_KEY = "AIzaSyBl-xxxxxxxxxxxxx"; // Ensure API key is set
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize views
etPrompt = findViewById(R.id.etPrompt); // Input field for user text
tvResponse = findViewById(R.id.tvResponse); // TextView to display generated response
btnGenerate = findViewById(R.id.btnGenerate); // Button to trigger API call
// Set button click listener
btnGenerate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String userInput = etPrompt.getText().toString();
if (!userInput.isEmpty()) {
generateText(userInput); // Call API with user input
} else {
tvResponse.setText("Please enter a prompt.");
}
}
});
}
private void generateText(String prompt) {
// Initialize the GenerativeModel
GenerativeModel model = new GenerativeModel(MODEL_NAME, API_KEY);
// Call the generateContent method asynchronously
model.generateContent(prompt, new Continuation<GenerateContentResponse>() {
@Override
public void resumeWith(Object result) {
if (result instanceof GenerateContentResponse) {
Content content = ((GenerateContentResponse) result).getCandidates().get(0).getContent();
if (content != null) {
Log.d("GeminiAPI", "Generated Response: " + content.getParts().get(0).toString());
runOnUiThread(() -> tvResponse.setText(((TextPart) content.getParts().get(0)).getText()));
}
} else if (result instanceof Throwable) {
Log.e("GeminiAPI", "Error generating response", (Throwable) result);
}
}
@Override
public CoroutineContext getContext() {
return EmptyCoroutineContext.INSTANCE; // Required for Kotlin coroutines
}
});
}
}
plugins {
alias(libs.plugins.android.application)
}
android {
namespace = "com.programmerworld.gemini20modelinandroid"
compileSdk = 35
defaultConfig {
applicationId = "com.programmerworld.gemini20modelinandroid"
minSdk = 33
targetSdk = 35
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
buildFeatures {
buildConfig = true // ? Enable BuildConfig generation
}
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
}
dependencies {
implementation(libs.appcompat)
implementation(libs.material)
implementation(libs.activity)
implementation(libs.constraintlayout)
testImplementation(libs.junit)
androidTestImplementation(libs.ext.junit)
androidTestImplementation(libs.espresso.core)
implementation("com.google.ai.client.generativeai:generativeai:0.9.0")
}
[versions]
agp = "8.8.0"
junit = "4.13.2"
junitVersion = "1.2.1"
espressoCore = "3.6.1"
appcompat = "1.7.0"
material = "1.12.0"
activity = "1.10.0"
constraintlayout = "2.2.0"
[libraries]
junit = { group = "junit", name = "junit", version.ref = "junit" }
ext-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }
material = { group = "com.google.android.material", name = "material", version.ref = "material" }
activity = { group = "androidx.activity", name = "activity", version.ref = "activity" }
constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraintlayout" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Gemini20ModelInAndroid"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/etPrompt"
android:layout_width="381dp"
android:layout_height="60dp"
android:hint="Enter your prompt here"
android:inputType="text" />
<Button
android:id="@+id/btnGenerate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Generate Response"
android:layout_marginTop="16dp"/>
<TextView
android:id="@+id/tvResponse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Response will appear here"
android:textSize="18sp"
android:layout_marginTop="16dp"/>
</LinearLayout>
Screenshots:


For API Key, visit Google AI studio: https://aistudio.google.com/prompts/new_chat


Complete project folder available at: https://drive.google.com/file/d/1RVNrAmZBDgZsVFxo5b3M4PKmvLpA3Hc0/view?usp=sharing