Search code examples
javatranslationgoogle-mlkit

How to check whether translation package is already installed? Java & Google ML-KIT


I am coding an app that translated while typing, but for it to work, it needs to install a package for the translation to happen. Is there a way to check whether the package has already been installed, and do something, and if the package that needs to be installed isn't installed it would do something else.

For example, if I want to translate from English to Spanish, but I don't have the package installed, I need show a dialog to let the user know that the package is installing.

Here is the function of translating:

private void translate(String textToTranslate) {
    /*
    PleaseWaitDialog progressDialog = new PleaseWaitDialog(this);
    progressDialog.setEnterTransition(R.anim.fade_in);
    progressDialog.setExitTransition(R.anim.fade_out);
    progressDialog.setHasOptionsMenu(true);
    progressDialog.setCancelable(true);
    progressDialog.setProgressStyle(PleaseWaitDialog.ProgressStyle.LINEAR);
    progressDialog.setTitle("Installing Translation Model");
    progressDialog.setMessage("This is done to speed up the translation, next time you use this. Next time you translate, " +
            "translation will happen in a few seconds, skipping this process");
    progressDialog.show();
     */

    TranslatorOptions options = new TranslatorOptions.Builder()
            .setTargetLanguage(languageTranslateTo)
            .setSourceLanguage(languageTranslateFrom)
            .build();
    Translator translator = Translation.getClient(options);
    
    translator.downloadModelIfNeeded()
            .addOnSuccessListener(unused -> {
                //progressDialog.dismiss();
                translateWithModelAvailable(translator, textToTranslate);
            })
            .addOnFailureListener(e -> {
                //progressDialog.dismiss();
                Log.e(TAG, "Translation model download failed: " + e.getMessage());
                new MaterialAlertDialogBuilder(TextTranslateActivity.this)
                        .setMessage("Translation Failed. There may be a problem with installing the translation model.")
                        .setPositiveButton("OK", null)
                        .show();
            });
}

Solution

  • You can refer to the ML Kit dev doc, e.g. https://developers.google.com/ml-kit/language/translation/android#manage-models