Using Gemini AI in Android Apps with the New Google AI SDK

MMS Founder
MMS Sergio De Simone

Article originally posted on InfoQ. Visit InfoQ

Google introduced its new Google AI SDK to simplify integrating Gemini Pro, its best-performing model to date, in Android apps. Using this SDK, developers need not build and manage their own backend infrastructure.

According to Google, Gemini Pro is their best model with features for a wide range of text and image reasoning tasks. Gemini Pro runs off-device, in Google’s data centers, and can be accessed through the Gemini API. The easiest way to use Gemini, says Google, is with Google AI Studio, a web-based tool that enables prototyping and running prompts in a browser. Once your results are satisfactory, you can export your model to code and use it in your preferred language, for example, Python, running on your backend.

For Android apps, Google is providing the Google AI client SDK for Android, which wraps Gemini REST API into an idiomatic Kotlin API. Using it, developers will not need to work directly with the REST API nor implement a server-side service for accessing Gemini models in Android apps.

The following snippet shows how you can generate text from a text-only prompt using the Google AI SDK:

val generativeModel = GenerativeModel(
    modelName = "gemini-pro",
    apiKey = BuildConfig.apiKey
)

val prompt = "Write a story about a magic backpack."
val response = generativeModel.generateContent(prompt)
print(response.text)

In addition to its text-only model, Gemini also provides a multimodal model able to generate text from text-and-image input (gemini-pro-vision) and supports streaming for faster interactions. In this case, you would use generateContentStream instead of generateContent, as shown below:

var fullResponse = ""
generativeModel.generateContentStream(inputContent).collect { chunk ->
    print(chunk.text)
    fullResponse += chunk.text
}

To further simplify developers’ workflow, the latest preview of Android Studio introduces a new project template that will guide developers through the steps required to use Gemini Pro, starting with generating an API key in Google AI Studio.

Besides Gemini Pro, Google is also providing a smaller model, Gemini Nano, which can be run on-device. This enables applications where data should never leave the device and ensures predictable latency, even when the network is not available. Gemini Nano is available on select devices through AICore a new system service for Android 14 that aims to simplify incorporating AI in Android apps by taking care of model management, runtime, safety, and more.

About the Author

Subscribe for MMS Newsletter

By signing up, you will receive updates about our latest information.

  • This field is for validation purposes and should be left unchanged.