The execution of the synchronous method may take a long time. To avoid slow response and no response, do not directly call the synchronous method in the UI thread.
With the support of an on-device model, the on-device translation service can translate text from the source language into the target language when no Internet service is available. Currently, this service supports text in 54 languages. For details, please refer to Languages Supported by Translation.
Similar to the real-time translation service, the on-device translation service can be widely used in scenarios where translation between different languages is required. For example, travel apps can integrate this service to translate road signs and menus in other languages into tourists' native languages, providing more considerate services for them. Different from real-time translation, on-device translation does not require the Internet connection. You can easily use the translation service even if the Internet is disconnected.
To use the on-device translation service, you need to download translation models for both the source language and target language.
Before app development, you need to make necessary development preparations, configure the Maven repository address for the HMS Core SDK, and integrate the on-device translation SDK.
- // Create an offline translator.
- MLLocalTranslateSetting setting = new MLLocalTranslateSetting.Factory()
- // Set the source language code. The ISO 639-1 standard is used. This parameter is mandatory. If this parameter is not set, an error may occur.
- .setSourceLangCode("zh")
- // Set the target language code. The ISO 639-1 standard is used. This parameter is mandatory. If this parameter is not set, an error may occur.
- .setTargetLangCode("en")
- .create();
- final MLLocalTranslator mlLocalTranslator = MLTranslatorFactory.getInstance().getLocalTranslator(setting);
- // Create an offline translator.
- val setting = MLLocalTranslateSetting.Factory() // Set the source language code. The ISO 639-1 standard is used. This parameter is mandatory. If this parameter is not set, an error may occur.
- .setSourceLangCode("zh") // Set the target language code. The ISO 639-1 standard is used. This parameter is mandatory. If this parameter is not set, an error may occur.
- .setTargetLangCode("en")
- .create()
- val mlLocalTranslator = MLTranslatorFactory.getInstance().getLocalTranslator(setting)
- MLTranslateLanguage.getLocalAllLanguages().addOnSuccessListener(
- new OnSuccessListener<Set<String>>() {
- @Override
- public void onSuccess(Set<String> result) {
- // Languages supported by on-device translation are successfully obtained.
- }
- });
- MLTranslateLanguage.getLocalAllLanguages().addOnSuccessListener { // Languages supported by on-device translation are successfully obtained.
- }
- Set<String> result = MLTranslateLanguage.syncGetLocalAllLanguages();
- val result = MLTranslateLanguage.syncGetLocalAllLanguages()
- // After the download is successful, translate text in the onSuccess callback.
- // Obtain the model manager.
- MLLocalModelManager manager = MLLocalModelManager.getInstance();
- MLLocalTranslatorModel model = new MLLocalTranslatorModel.Factory(sourceLangCode).create();
- // Set the model download policy.
- MLModelDownloadStrategy downloadStrategy = new MLModelDownloadStrategy.Factory()
- .needWifi() // It is recommended that you download the package in a Wi-Fi environment.
- // Set the site region. Currently, the following values are supported: REGION_DR_CHINA, REGION_DR_GERMAN, REGION_DR_SINGAPORE, and REGION_DR_RUSSIA. (The site region must be the same as the access site selected in AppGallery Connect.)
- .setRegion(MLModelDownloadStrategy.REGION_DR_CHINA)
- .create();
- // Create a download progress listener.
- MLModelDownloadListener modelDownloadListener = new MLModelDownloadListener() {
- @Override
- public void onProcess(long alreadyDownLength, long totalLength) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- // Display the download progress or perform other operations.
- }
- });
- }
- };
- // Download the model. After the model is downloaded, translate text in the onSuccess callback.
- manager.downloadModel(model, downloadStrategy, modelDownloadListener).addOnSuccessListener(new OnSuccessListener<Void>() {
- @Override
- public void onSuccess(Void aVoid) {
- // Called when the model package is successfully downloaded.
- }
- }).addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(Exception e) {
- // Called when the model package fails to be downloaded.
- }
- });
- // After the download is successful, translate text in the onSuccess callback.
- // Obtain the model manager.
- val manager = MLLocalModelManager.getInstance()
- val sourceLangCode: String? = null
- val model = MLLocalTranslatorModel.Factory(sourceLangCode).create()
- // Set the model download policy.
- val downloadStrategy = MLModelDownloadStrategy.Factory()
- .needWifi() // It is recommended that you download the package in a Wi-Fi environment.
- .create()
- // Create a download progress listener.
- val modelDownloadListener = MLModelDownloadListener { alreadyDownLength, totalLength ->
- runOnUiThread {
- // Display the download progress or perform other operations.
- }
- }
- // Download the model. After the model is downloaded, translate text in the onSuccess callback.
- manager.downloadModel(model, downloadStrategy, modelDownloadListener).addOnSuccessListener {
- // Called when the model package is successfully downloaded.
- }.addOnFailureListener {
- // Called when the model package fails to be downloaded.
- }
- // Set the model download policy.
- MLModelDownloadStrategy downloadStrategy = new MLModelDownloadStrategy.Factory()
- .needWifi() // It is recommended that you download the package in a Wi-Fi environment.
- .create();
- // Create a download progress listener.
- MLModelDownloadListener modelDownloadListener = new MLModelDownloadListener() {
- @Override
- public void onProcess(long alreadyDownLength, long totalLength) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- // Display the download progress or perform other operations.
- }
- });
- }
- };
- mlLocalTranslator.preparedModel(downloadStrategy, modelDownloadListener).
- addOnSuccessListener(new OnSuccessListener<Void>() {
- @Override
- public void onSuccess (Void aVoid){
- // Called when the model package is successfully downloaded.
- }
- }).addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure (Exception e){
- // Called when the model package fails to be downloaded.
- }
- });
- // Set the model download policy.
- val downloadStrategy = MLModelDownloadStrategy.Factory()
- .needWifi() // It is recommended that you download the package in a Wi-Fi environment.
- .create()
- // Create a download progress listener.
- val modelDownloadListener = MLModelDownloadListener { alreadyDownLength, totalLength ->
- runOnUiThread {
- // Display the download progress or perform other operations.
- }
- }
- val mlLocalTranslator: MLLocalTranslator? = null
- mlLocalTranslator!!.preparedModel(downloadStrategy, modelDownloadListener).addOnSuccessListener {
- // Called when the model package is successfully downloaded.
- }.addOnFailureListener {
- // Called when the model package fails to be downloaded.
- }
- // input is a string of less than 5000 characters.
- final Task<String> task = mlLocalTranslator.asyncTranslate(input);
- // Before translation, ensure that the models have been successfully downloaded.
- task.addOnSuccessListener(new OnSuccessListener<String>() {
- @Override
- public void onSuccess(String s) {
- // Processing logic for detection success.
- }
- }).addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(Exception e) {
- // Processing logic for detection failure.
- }
- });
- // input is a string of less than 5000 characters.
- val input: String? = null
- val task = mlLocalTranslator.asyncTranslate(input)
- // Before translation, ensure that the model is successfully downloaded.
- task.addOnSuccessListener {
- // Processing logic for detection success.
- }.addOnFailureListener {
- // Processing logic for detection failure.
- }
- try {
- // input is a string of less than 5000 characters.
- String output = mlLocalTranslator.syncTranslate(input);
- // Processing logic for detection success.
- } catch (MLException e) {
- // Processing logic for detection failure.
- }
- try {
- // input is a string of less than 5000 characters.
- val output = mlLocalTranslator.syncTranslate(input)
- // Processing logic for detection success.
- } catch (e: MLException) {
- // Processing logic for recognition failure.
- }
The execution of the synchronous method may take a long time. To avoid slow response and no response, do not directly call the synchronous method in the UI thread.
- // Obtain the model manager.
- MLLocalModelManager manager = MLLocalModelManager.getInstance();
- MLLocalTranslatorModel model = new MLLocalTranslatorModel
- .Factory("zh") // Set the target language code for the model, which complies with the ISO 639-1 standard.
- .create();
- // Delete a model package.
- manager.deleteModel(model).addOnSuccessListener(new OnSuccessListener<Void>() {
- public void onSuccess(Void aVoid) {
- // Called when the model package is successfully deleted.
- }
- }).addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(Exception e) {
- // Called when the model package fails to be deleted.
- }
- });
- // Obtain the model manager.
- val manager = MLLocalModelManager.getInstance()
- val model = MLLocalTranslatorModel.Factory("zh") // Set the target language code for the model. The ISO 639-1 standard is used.
- .create()
- // Delete a model package.
- manager.deleteModel(model).addOnSuccessListener {
- // Called when the model package is successfully deleted.
- }.addOnFailureListener {
- // Called when the model package fails to be deleted.
- }
-
-
- if (mlLocalTranslator!= null) {
- mlLocalTranslator.stop();
- }
- if (mlLocalTranslator != null) {
- mlLocalTranslator.stop()
- }
Before downloading an on-device model, you need to understand the download principle and how to use the on-device model. For details, please refer to How to Download and Use an On-device Model.