Translate text with ML Kit on Android

  • ML Kit can translate text between more than 50 languages using on-demand dynamic model downloads.

  • You need to create a Translator object, download the necessary language model, and then use the translate() method to translate text.

  • Explicit model management allows you to pre-download, delete, and control language models on the device for optimized performance.

  • It's recommended to download models over Wi-Fi and delete unused models to save storage space and bandwidth.

  • Ensure the close() method is called when the Translator object is no longer needed, potentially using LifecycleObserver for easier management in Fragments or Activities.

You can use ML Kit to translate text between languages. ML Kit can translation between more than 50 languages.

Try it out

  • Play around with the sample app to see an example usage of this API.

Before you begin

  1. In your project-level build.gradle file, make sure to include Google's Maven repository in both your buildscript and allprojects sections.
  2. Add the dependencies for the ML Kit Android libraries to your module's app-level gradle file, which is usually app/build.gradle:
    dependencies {
      // ...
    
      implementation 'com.google.mlkit:translate:17.0.3'
    }

Translate a string of text

To translate a string between two languages:

  1. Create a Translator object, configuring it with the source and target languages:

    Kotlin

    // Create an English-German translator:
    val options = TranslatorOptions.Builder()
        .setSourceLanguage(TranslateLanguage.ENGLISH)
        .setTargetLanguage(TranslateLanguage.GERMAN)
        .build()
    val englishGermanTranslator = Translation.getClient(options)

    Java

    // Create an English-German translator:
    TranslatorOptions options =
        new TranslatorOptions.Builder()
            .setSourceLanguage(TranslateLanguage.ENGLISH)
            .setTargetLanguage(TranslateLanguage.GERMAN)
            .build();
    final Translator englishGermanTranslator =
        Translation.getClient(options);

    If you don't know the language of the input text, you can use the Language Identification API which gives you a language tag. Then convert the tag to a TranslateLanguage using TranslateLanguage.fromLanguageTag().

    Avoid keeping too many language models on the device at once.

  2. Make sure the required translation model has been downloaded to the device. Don't call translate() until you know the model is available.

    Kotlin

    var conditions = DownloadConditions.Builder()