You can use ML Kit to translate text between languages. ML Kit
can translation between more than
[50 languages](https://developers.google.com/ml-kit/languages/translation/translation-language-support).

<br />

This API supports on demand dynamic model downloads. See [this guide](https://developers.google.com/ml-kit/tips/installation-paths.md.txt) for more information.

## Try it out

- Play around with [the sample app](https://github.com/googlesamples/mlkit/tree/master/android/translate) to see an example usage of this API.

## Before you begin

> [!NOTE]
> This API requires Android API level 23 or above. Make sure that your app's build file uses a `minSdkVersion` value of 23 or higher.

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`](https://developers.google.com/android/reference/com/google/mlkit/nl/translate/Translator.md.txt)
   object, configuring it with the source and target languages:

   ### Kotlin

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

   ### Java

   ```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](https://developers.google.com/ml-kit/language/identification) which
   gives you a language tag. Then convert the tag to a `TranslateLanguage`
   using [`TranslateLanguage.fromLanguageTag()`](https://developers.google.com/android/reference/com/google/mlkit/nl/translate/TranslateLanguage.md.txt#public-static-string-fromlanguagetag-string-languagetag).

   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

   ```kotlin
   var conditions = DownloadConditions.Builder()
       .requireWifi()
       .build()
   englishGermanTranslator.downloadModelIfNeeded(conditions)
       .addOnSuccessListener {
           // Model downloaded successfully. Okay to start translating.
           // (Set a flag, unhide the translation UI, etc.)
       }
       .addOnFailureListener { exception ->
           // Model couldn't be downloaded or other internal error.
           // ...
       }
   ```

   ### Java

   ```java
   DownloadConditions conditions = new DownloadConditions.Builder()
       .requireWifi()
       .build();
   englishGermanTranslator.downloadModelIfNeeded(conditions)
       .addOnSuccessListener(
           new OnSuccessListener() {
             @Override
             public void onSuccess(Void v) {
               // Model downloaded successfully. Okay to start translating.
               // (Set a flag, unhide the translation UI, etc.)
             }
           })
       .addOnFailureListener(
           new OnFailureListener() {
             @Override
             public void onFailure(@NonNull Exception e) {
               // Model couldn't be downloaded or other internal error.
               // ...
             }
           });
   ```

   Language models are around 30MB, so don't download them unnecessarily, and
   only download them using Wi-Fi unless the user has specified otherwise. You
   should also delete unneeded models.
   See [Explicitly manage translation models](https://developers.google.com/ml-kit/language/translation/android.md.txt#manage-models).
3. After you confirm the model has been downloaded, pass a string of text in
   the source language to
   [`translate()`](https://developers.google.com/android/reference/com/google/mlkit/nl/translate/Translator.md.txt#public-taskstring-translate-string-input):

   ### Kotlin

   ```kotlin
   englishGermanTranslator.translate(text)
       .addOnSuccessListener { translatedText ->
           // Translation successful.
       }
       .addOnFailureListener { exception ->
            // Error.
            // ...
       }
   ```

   ### Java

   ```java
   englishGermanTranslator.translate(text)
       .addOnSuccessListener(
           new OnSuccessListener() {
             @Override
             public void onSuccess(@NonNull String translatedText) {
               // Translation successful.
             }
           })
       .addOnFailureListener(
           new OnFailureListener() {
             @Override
             public void onFailure(@NonNull Exception e) {
               // Error.
               // ...
             }
           });
   ```

   The translated text, in the target language you configured, is passed to the
   success listener.
4. Ensure that the [`close()`](https://developers.google.com/android/reference/com/google/mlkit/nl/translate/Translator.md.txt#public-void-close)
   method is called when the
   [`Translator`](https://developers.google.com/android/reference/com/google/mlkit/nl/translate/Translator.md.txt)
   object will no longer be used.

   If you are using a Translator in a Fragment or AppCompatActivity, one easy
   way to do that is call [LifecycleOwner.getLifecycle()](https://developer.android.com/reference/androidx/lifecycle/LifecycleOwner#getLifecycle())
   on the Fragment or AppCompatActivity, and then call [Lifecycle.addObserver](https://developer.android.com/reference/androidx/lifecycle/Lifecycle#addObserver(androidx.lifecycle.LifecycleObserver)).
   For example:

   ### Kotlin

   ```kotlin
   val options = ...
   val translator = Translation.getClient(options)
   getLifecycle().addObserver(translator)
   ```

   ### Java

   ```java
   TranslatorOptions options = ...
   Translator translator = Translation.getClient(options);
   getLifecycle().addObserver(translator);
   ... use translator ...
   ```

   Note that this assumes that the code is inside of a class that implements
   LifecycleOwner (e.g. a Fragment or AppCompatActivity).

## Explicitly manage translation models


When you use the translation API as described above, ML Kit automatically
downloads language-specific translation models to the device as required. You
can also explicitly manage the translation models you want available on the
device by using ML Kit's translation model management API. This can be
useful if you want to download models ahead of time, or delete unneeded models
from the device.

<br />

### Kotlin

```kotlin
val modelManager = RemoteModelManager.getInstance()

// Get translation models stored on the device.
modelManager.getDownloadedModels(TranslateRemoteModel::class.java)
    .addOnSuccessListener { models ->
        // ...
    }
    .addOnFailureListener {
        // Error.
    }

// Delete the German model if it's on the device.
val germanModel = TranslateRemoteModel.Builder(TranslateLanguage.GERMAN).build()
modelManager.deleteDownloadedModel(germanModel)
    .addOnSuccessListener {
        // Model deleted.
    }
    .addOnFailureListener {
        // Error.
    }

// Download the French model.
val frenchModel = TranslateRemoteModel.Builder(TranslateLanguage.FRENCH).build()
val conditions = DownloadConditions.Builder()
    .requireWifi()
    .build()
modelManager.download(frenchModel, conditions)
    .addOnSuccessListener {
        // Model downloaded.
    }
    .addOnFailureListener {
        // Error.
    }
```

### Java

```java
RemoteModelManager modelManager = RemoteModelManager.getInstance();

// Get translation models stored on the device.
modelManager.getDownloadedModels(TranslateRemoteModel.class)
    .addOnSuccessListener(new OnSuccessListener<Set>() {
        @Override
        public void onSuccess(Set models) {
            // ...
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            // Error.
        }
    });

// Delete the German model if it's on the device.
TranslateRemoteModel germanModel =
        new TranslateRemoteModel.Builder(TranslateLanguage.GERMAN).build();
modelManager.deleteDownloadedModel(germanModel)
    .addOnSuccessListener(new OnSuccessListener() {
        @Override
        public void onSuccess(Void v) {
            // Model deleted.
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            // Error.
        }
    });

// Download the French model.
TranslateRemoteModel frenchModel =
        new TranslateRemoteModel.Builder(TranslateLanguage.FRENCH).build();
DownloadConditions conditions = new DownloadConditions.Builder()
    .requireWifi()
    .build();
modelManager.download(frenchModel, conditions)
    .addOnSuccessListener(new OnSuccessListener() {
        @Override
        public void onSuccess(Void v) {
            // Model downloaded.
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            // Error.
        }
    });
```