“Breaking Language Barriers: Using Google ML Kit Translation in Android Apps”

Yash Mittal
4 min readJan 29, 2025

--

In today’s connected world, apps need to support multiple languages to be more user-friendly and inclusive. Google’s ML Kit Translation API makes this easy by offering fast, offline translations that integrate smoothly into Android apps. In this article, we’ll look at why this API is a great choice and show you how to add a simple translation feature using Jetpack Compose.

Benefits of Google ML Kit Translation API

  1. Works Offline — No internet? No problem! Download language models and translate text anytime.
  2. Auto-Detects Language — No need to pick a language manually; the API figures it out for you.
  3. Easy for Android Apps — Integrates smoothly with Jetpack Compose for a great user experience.
  4. Fast & Lightweight — Translates on your device, avoiding slow internet-based services.

Implementing Google ML Kit Translation API in Jetpack Compose

1. Setup Dependencies

First, add the required dependencies in your build.gradle file:

dependencies {
implementation(libs.translate) // ML Kit Translation API
implementation(libs.language.id) // ML Kit Language Identification API
implementation(libs.kotlinx.coroutines.play.services) // For coroutine support
}

2. Create a Translator Function

The following function uses ML Kit to detect the source language and translate text into a target

uspend fun translateText(input: String, targetLang: String): String {
val languageIdentifier = LanguageIdentification.getClient()
val detectedLanguage = languageIdentifier.identifyLanguage(input).await()

val translatorOptions = TranslatorOptions.Builder()
.setSourceLanguage(detectedLanguage)
.setTargetLanguage(targetLang)
.build()

val translator = Translation.getClient(translatorOptions)

return try {
val conditions = DownloadConditions.Builder().requireWifi().build()
translator.downloadModelIfNeeded(conditions).await()
translator.translate(input).await()
} catch (exception: Exception) {
"Translation failed: ${exception.localizedMessage}"
} finally {
translator.close()
}
}

Step-by-Step Breakdown

This function, translateText, is a suspend function that translates a given text into a specified target language using Google ML Kit’s On-Device Translation API. It follows these key steps:

1. Function Definition

suspend fun translateText(input: String, targetLang: String): String {
  • The function is suspend, meaning it runs asynchronously and should be called inside a coroutine.
  • It takes two parameters:
  • input: The text to be translated.
  • targetLang: The language code of the target language (e.g., "es" for Spanish, "hi" for Hindi).

2. Detect the Source Language

val languageIdentifier: LanguageIdentifier = LanguageIdentification.getClient()
val detectedLanguage = languageIdentifier.identifyLanguage(input).await()
  • It initializes languageIdentifier using ML Kit's Language Identification API.
  • It detects the language of the input text using identifyLanguage(input).await(), which runs asynchronously.

⚠️ Potential Issue: If the detected language is "und" (undetermined), you may need to handle this case separately.

3. Configure the Translator

val translatorOptions = TranslatorOptions.Builder()
.setSourceLanguage(detectedLanguage)
.setTargetLanguage(targetLang)
.build(
  • Creates translation options using TranslatorOptions.Builder().
  • Sets:
  • setSourceLanguage(detectedLanguage): The detected language.
  • setTargetLanguage(targetLang): The target language for translation.

4. Create the Translator Client

val translator = Translation.getClient(translatorOptions)
  • This initializes an ML Kit Translator client using the defined translatorOptions.

5. Download the Language Model (if needed)

val conditions = DownloadConditions.Builder()
.requireWifi()
.build()
translator.downloadModelIfNeeded(conditions).await()
  • It ensures the translation model is downloaded before translating:
  • requireWifi(): Ensures the download happens only over Wi-Fi (to avoid using mobile data).
  • .await() ensures the operation completes before proceeding.

⚠️ If the model is not already downloaded, it will be fetched and stored on-device.

6. Perform the Translation

translator.translate(input).await()
  • Translates the input text asynchronously.

7. Handle Errors

catch (exception: Exception) {
"Translation failed: ${exception.localizedMessage}"
}
  • If any error occurs (e.g., no internet connection, model not found, etc.), it returns "Translation failed: <error message>".

8. Clean Up Resources

finally {
translator.close()
}
  • The translator.close() method releases resources to prevent memory leaks.

Optimized Approach 💻:

Preload and Cache Language Models 🚀

To speed up translations, preload ML models instead of downloading them at runtime:

1️⃣ Store supported languages in a local JSON file (e.g., languages.json).
2️⃣ Preload translation models on app launch using TranslationModelManager.
3️⃣ Skip downloads during translation by using cached models for instant results.

This ensures offline support, faster translations, and reduced API calls. ✅

Conclusion

Google’s ML Kit Translation API makes it easy to add real-time translation to Android apps. It works offline, detects languages automatically, and integrates smoothly with Jetpack Compose — all without needing costly cloud services.

Whether you’re building a travel app, an online store, or a social media platform, this API helps make your app more user-friendly and accessible worldwide.

If you found this guide useful, share it and drop your thoughts in the comments!

Photo by Wilhelm Gunkel on Unsplash

--

--

Yash Mittal
Yash Mittal

Written by Yash Mittal

Frustrated coder, cooking code, burning hands and repeating recursively until a delicious dish pop out of my kitchen to be served as innovation.

No responses yet