I'd like to localize or event better change the prompt text of User Consent API.
Default behavior:
So instead of Allow example to read the message below and enter the code I want it to be translated in other languages, based on my app's locale not based on device's locale.
This view's translation is handled by the library gms:play-services-auth-api-phone.
Didn 't find any information in their documentation explaining how to customize the message displayed in the bottomSheetView.
About the language of the message, it should update automatically depending on the phone's language.
Since you're receiving an intent from another app, chances are that you won't be able to 'force' a locale sadly.
The only thing you could try is to "force" the Locale on the Android part in your FlutterActivity but note that it could have unpredicted consequences over your app, and I really doubt it'll work.
private void setLocale(Locale locale){
SharedPrefUtils.saveLocale(locale); // optional - Helper method to save the selected language to SharedPreferences in case you might need to attach to activity context (you will need to code this)
Resources resources = getResources();
Configuration configuration = resources.getConfiguration();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
configuration.setLocale(locale);
} else{
configuration.locale=locale;
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N){
getApplicationContext().createConfigurationContext(configuration);
} else {
resources.updateConfiguration(configuration,displayMetrics);
}
}
Code retrieved from this StackOverflow post, credit to the author.
Related
I've a problem with AAB when I need to change the app locale from within the app itself(i.e. have the language change setting inside the app), the issue is that the AAB gives me only my device languages resources, for example:
my device has English and French languages installed in it, so AAb gives me only the resources for English and French,
but from within the app itself there is a choice to switch the language between English, French, and Indonesian,
in that case, when changing the language to English or French everything is working perfectly, but when changing it to Indonesian, the app simply enters a crash loop as it keep looking for Indonesian language but it can't find.
The problem here is that even if I restarted the app, it enters the crash loop again as the app is still looking for the missing language resources, and here the only solution is to clear cash or reinstall which are the solutions that the normal user won't go through.
Just to mention it, this is how I change the locale through the app:
// get resources
Resources res = context.getResources();
// create the corresponding locale
Locale locale = new Locale(language); // for example "en"
// Change locale settings in the app.
android.content.res.Configuration conf = res.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
conf.setLocale(locale);
conf.setLayoutDirection(locale);
} else {
conf.locale = locale;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
context.getApplicationContext().createConfigurationContext(conf);
}
res.updateConfiguration(conf, null);
P.S. The app is working perfectly when build it as APK.
Edit:
The PlayCore API now supports downloading the strings for another language on-demand:
https://developer.android.com/guide/playcore/feature-delivery/on-demand#lang_resources
Alternative solution (discouraged):
You can disable the splitting by language by adding the following configuration in your build.gradle
android {
bundle {
language {
// Specifies that the app bundle should not support
// configuration APKs for language resources. These
// resources are instead packaged with each base and
// dynamic feature APK.
enableSplit = false
}
}
}
This latter solution will increase the size of the app.
This is not possible with app bundles: Google Play only downloads resources when the device's selected languages change.
You'll have to use APKs if you want to have an in app language picker.
Details of downloading the language on demand can be found here
https://android-developers.googleblog.com/2019/03/the-latest-android-app-bundle-updates.html
In your app’s build.gradle file:
dependencies {
// This dependency is downloaded from the Google’s Maven repository.
// So, make sure you also include that repository in your project's build.gradle file.
implementation 'com.google.android.play:core:1.10.0'
// For Kotlin users also add the Kotlin extensions library for Play Core:
implementation 'com.google.android.play:core-ktx:1.8.1'
...
}
Get a list of installed languages
val splitInstallManager = SplitInstallManagerFactory.create(context)
val langs: Set<String> = splitInstallManager.installedLanguages
Requesting additional languages
val installRequestBuilder = SplitInstallRequest.newBuilder()
installRequestBuilder.addLanguage(Locale.forLanguageTag("pl"))
splitInstallManager.startInstall(installRequestBuilder.build())
Check above link for full details
After many hours I was finally able to use the on-demand language with the new PlayCore API.
Step 1.) As the user changes the language, you need to first check whether the language is already available, if not then download the language
private void changeLocale(final String languageSelected){
SplitInstallManager splitInstallManager = SplitInstallManagerFactory.create(PlayAgainstComputer.this);
final Set<String> installedLangs = splitInstallManager.getInstalledLanguages();
if(installedLangs.contains(languageSelected)){ // checking if lang already available
Toast.makeText(PlayAgainstComputer.this,"Done! The language settings will take effect, once you restart the app!").show();
}
else{
SplitInstallRequest request =
SplitInstallRequest.newBuilder()
.addLanguage(Locale.forLanguageTag(languageSelected))
.build();
splitInstallManager.startInstall(request);
splitInstallManager.registerListener(new SplitInstallStateUpdatedListener() {
#Override
public void onStateUpdate(#NonNull SplitInstallSessionState splitInstallSessionState) {
if(splitInstallSessionState.status() == SplitInstallSessionStatus.INSTALLED){
Toast.makeText(PlayAgainstComputer.this,"Download complete! The language settings will take effect, once you restart the app!").show();
}
}
});
}}
Step2.) The downloaded languages must be installed when the user starts the app. which is done in the attchBaseContext() method
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
SplitCompat.install(this); // It will install all the downloaded langauges into the app
}
Step 3.) You need to tell the Activity to use the chosen language. Following code should be placed before setContentView(R.layout.layout); of that activity
String selectedLanguage = getFromPrefernceOrWhereEverYouSavedIt(); // should be 2 letters. like "de", "es"
Locale locale = new Locale(selectedLanguage);
Locale.setDefault(locale);
Resources resources = getResources();
Configuration config = new Configuration(resources.getConfiguration());
config.locale = locale;
resources.updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
Done!
Please Note
When a user (who chose a non-default/downloaded language) updates the app, that language needs to be downloaded again into the app, so make sure you handle that in your code.
when I used activity.recreate(); after the download finished (to automatically refresh the app for new language) I faced some problems, that is why I used Toast to ask the user to manually restart the app. but you can try other methods
I also noticed some other inconsistencies (even sometimes faced memory leak because of SplitCompat.install(this);) with this method, so make sure you test and optimize it according to your code.
I override the Locale of my Android App at startup and allow to change the region at runtime.
I'm settings the Locale like this:
Resources res = context.getResources();
Configuration configuration = res.getConfiguration();
DisplayMetrics metrics = res.getDisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLocale(locale);
}else{
configuration.locale = locale;
}
Locale.setDefault(locale);
res.updateConfiguration(configuration, metrics);
Now i want to use Firebase-Remote-Config with a Region/Country Condition.
e.g.
test_property -> fr_FR = Bonjour
-> de_DE = Hallo
-> default = Hi
If i now have my Device set to de_DE and my app set to fr_FR i will get the test_property from the de_DE region (Hallo).
What i want to get is the test_property for the region fr_FR set by the app.
I tried to FirebaseApp.initializeApp(...) after changing the region in the app, but Firebase seems to get the region from somewhere else.
Does someone know a way to set/override the region programmatically so firebase will use that region for the region condition?
I don't want to use Firebase Analytics User Properties, as they get updated way too late.
In your Firebase Console:
a) Set a user property for locale. Go to Analytics menu and select USER PROPERTIES tab.
Provide user property name. Like user_locale.
Add description, save, and publish changes.
b) Set a condition for remote configs. Go to Remote Config menu and select CONDITIONS tab.
Select User property - user_locale.
Select FOR TEXT - exactly matches.
Put locale you need. Like de for German.
Put name like translation_de for condition and select a color.
Save and publish changes.
c) For every remote config parameter add value for condition.
From drop down menu select appropriate condition like translation_de.
Update and publish changes.
On locale change in your code set User Property
FirebaseAnalytics.getInstance(getContext())
.setUserProperty("user_locale", "de");
FirebaseRemoteConfig.getInstance()
.fetch(1)
.addOnCompleteListener(activity, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
FirebaseRemoteConfig.getInstance().activateFetched();
}
}
});
...and if so, how?
We make a dedicated Android device for use in an industrial environment. It's basically a tablet, but with only one app running. The user is not expected to access any other features of the device and even the system settings, like WiFi and Time settings are performed through our app instead of through the Android Settings widget. So basically every button and message they see uses our strings.xml file.
Currently all of our customers are satisfied to use the default US-English settings but we will soon have some customers who want local languages and have supplied us with translation files. Currently one of them is Romanian, which is not a language with any native support on this device (a Samsung Galaxy tab 4); another is Czech.
So we want to add strings.xml files in appropriate res folders, for the non-English languages and a dropdown in our app to select which language we're using. Programmatically we think we can use Locale to set which strings.xml file it uses, so for example, if Romanian has been selected from the dropdown we would use Locale to set the tablet into Romanian so all of our app's UI will use the Romanian strings.xml file.
Our settings, including the new dropdown, are inaccessible to customers - they're set at the customer site by a field-service engineer.
Questions:
Will this work? I.e., can we control which strings.xml file it uses via Locale, even if the device has no native support for that language?
Since Romanian is not a natively-supported language with this device we assume that system messages will still come up in English. Is this true? (it's not a problem if it does - system messages are rare with our app and the users of our products are trained to contact support if that happens. I just want to make sure that if we set the Locale to Romanian, or Czech or some other language without native support it won't crash the tablet if it does try to issue a system message).
Will this work? I.e., can we control which strings.xml file it uses via Locale, even if the device has no native support for that language?
Yes, you can, by updating Locale within Configuration (see an example below). If you try to use the locale for which there are no corresponding resources (either within your app or system), the default string resources (res/values/strings.xml) of your app will be utilized.
Since Romanian is not a natively-supported language with this device we assume that system messages will still come up in English. Is this true?
It is true, if English is the current system locale.
I just want to make sure that if we set the Locale to Romanian, or Czech or some other language without native support it won't crash the tablet if it does try to issue a system message.
Your app won't crash. Locale changes made within an app effect locale resources of the app, not system one's.
An example to answer "if so, how?" The method can be used to test locale changes while an Activity is running*.
public static void changeLocale(Context context, String locale) {
Resources res = context.getResources();
Configuration conf = res.getConfiguration();
conf.locale = new Locale(locale);
res.updateConfiguration(conf, res.getDisplayMetrics());
}
* You might want to call recreate() to see string resource changes "on the fly".
Yes you can definitely switch locale of single app. For that you have to extend every activity from a base class like following:
public abstract class MyLangActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
Locale locale = // get the locale to use...
Configuration conf = getResources().getConfiguration();
if (Build.VERSION.SDK_INT >= 17) {
conf.setLocale(locale);
} else {
conf.locale = locale;
}
DisplayMetrics metrics = getResources().getDisplayMetrics();
getResources().updateConfiguration(conf, metrics);
super.onCreate(savedInstanceState);
}
}
Now about the issue of device not supporting the language applied. The device font being used might not have support for characters in the custom language file. You might use your own fonts files to support that.
The best way to do this is to actually set the device locale. The code to do that is
Class<?> activityManagerNative = Class.forName("android.app.ActivityManagerNative");
Object am = activityManagerNative.getMethod("getDefault").invoke(activityManagerNative);
Object config = am.getClass().getMethod("getConfiguration").invoke(am);
config.getClass().getDeclaredField("locale").set(config, item.getLocale());
config.getClass().getDeclaredField("userSetLocale").setBoolean(config, true);
am.getClass().getMethod("updateConfiguration", android.content.res.Configuration.class).invoke(am, config);
ActivityManagerNative.java
package android.app;
public abstract class ActivityManagerNative implements IActivityManager {
public static IActivityManager getDefault(){
return null;
}
}
IActivityManager
package android.app;
import android.content.res.Configuration;
import android.os.RemoteException;
public interface IActivityManager {
public abstract Configuration getConfiguration () throws RemoteException;
public abstract void updateConfiguration (Configuration configuration) throws RemoteException;
}
This way you'll set the device locale, and let everything change through the normal pathways. You'll need the android:name="android.permission.CHANGE_CONFIGURATION" permission in your manifest. This is a secure permission, but installing yourself as a system app shouldn't be a problem for you.
Override getResources in Application and BaseActivity
#Override
public Resources getResources() {
if(mRes == null)
mRes = new PowerfulResources(getAssets(),new DisplayMetrics(), null);
return mRes;
}
public static class PowerfulResources extends Resources{
/**
* Create a new Resources object on top of an existing set of assets in an
* AssetManager.
*
* #param assets Previously created AssetManager.
* #param metrics Current display metrics to consider when
* selecting/computing resource values.
* #param config Desired device configuration to consider when
*/
public PowerfulResources(AssetManager assets, DisplayMetrics metrics, Configuration config) {
super(assets, metrics, config);
}
#NonNull
#Override
public String getString(int id) throws NotFoundException {
//do your stuff here
return super.getString(id);
}
}
also read this
original question
I have a standard texttospeech, android.speech.tts.TextToSpeech
I initialize it and set a language by using tts.setLanguage(Locale.getDefault())
That default Locale is de_DE (for germany, correct).
Right after setting it, i ask the tts to give me its language tts.getLanguage()
now it tells me that its set to "deu_DEU"
There is no Locale with that setting. So i cant even check if its set to the right language because i cant find the Locale object that has the matching values.
Issue might be related to Android 4.3, but i didnt find any info.
Background is, that i need to show values with the same decimal symbol, but tts needs the correct symbol or it says "dot" in german which makes NO sense at all.
Conclusion:
A Locale is a container that contains a string that is composed of a language, a country and an optional string. Every text-to-speech engine can return a custom Locale like "eng_USA_texas".
Furthermore the Locale that is returned by the tts engine can only be a "close match" to the wanted Locale. So "en_US" instead of "en_UK".
However, Locale has a method called getLanguage() and it returns the first part of above mentioned string. "en" or "eng". Those Language codes are regulated by ISO and one can hope that everyone sticks to it. (see link in the accepted answer)
So checking for tts.getLanguage().getLanguage().startsWith("en") should always be true if its some form of english language setting and the ISO standards are fulfilled.
It is important to mention that Locales should not be compared by locale_a == locale_b as both can be different objects yet have the same content, they are containers of sort.
Always compare with locale_a.equals(locale_b)
I hope this helps people sort out some problems with tts and language
You're right, it's frustrating how the locale codes the TTS object uses are different to those of the device locale. I don't understand why this decision was made.
To add further complication, the TTS Engine can supply all kinds of different locales, such as eng_US_sarah or en-US-female etc. It's down to the TTS Engine how these are stored and displayed.
I've had to write additional code to iterate through the returned locales and attempt to match them to the locale the system can use, or vica-versa.
To start with, take a look at how the engines you have installed are returning their locale information. You can then start to collate in your code a list to associate 'deu_DEU' to 'de_De'.
This is often simplistic by using split("_") & startsWith(String), but unfortunately not for all locales.
Here's some base code I've used to analyse the installed TTS Engines' locale structure.
private void getEngines() {
final Intent ttsIntent = new Intent();
ttsIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
final PackageManager pm = getActivity().getPackageManager();
final List<ResolveInfo> list = pm.queryIntentActivities(ttsIntent, PackageManager.GET_META_DATA);
final ArrayList<Intent> intentArray = new ArrayList<Intent>(list.size());
for (int i = 0; i < list.size(); i++) {
final Intent getIntent = new Intent();
getIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
getIntent.setPackage(list.get(i).activityInfo.applicationInfo.packageName);
getIntent.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES);
intentArray.add(getIntent);
}
for (int i = 0; i < intentArray.size(); i++) {
startActivityForResult(intentArray.get(i), i);
}
}
#Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
try {
if (data != null) {
System.out.print(data.getStringArrayListExtra("availableVoices").toString());
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
From the above ISO-3 codes and the device locale format, you should be able to come up with something for the locales you are concerned with.
I've been intending to submit an enhancement request to AOSP for a while, as all TTS Engines need to use constant values and extras such as gender etc need to be added to use the TTS Engines to their full capabilities.
EDIT: Further to your edit, note the wording regarding setLanguage(). The individual TTS Engine will try and match as close as possible to the requested locale, but that applied locale may be completely wrong, depending on how lenient the Engine provider is in their code and their response.
After creating an object of TextToSpeech class, you should configure it (or check it's available state/values) into TextToSpeech.OnInitListener's onInit() callback. You will get reliable information there about your TextToSpeech object.
Check my answer here:
https://stackoverflow.com/a/65620221/7835969
I've found using the android.text.format.DateUtils relative APIs that return values like "yesterday" or "2 hours ago" very nice - but my app does not support every language Android does. So, I default to English, but for every language I don't support, the relative string shows in the device's setting.
For example, like:
Last attempt: hace 11 minutos.
I'd like to make the API call default to English for any languages I don't support. However, I don't see anywhere to set the Locale for the API call - I'm hoping I'm just missing it somewhere.
Is there a way to set the Locale just for the API call, ignoring the device setting?
This is working for me up to Android 7
void forceLocale(Locale locale) {
Configuration conf = getBaseContext().getResources().getConfiguration();
updateConfiguration(conf, locale);
getBaseContext().getResources().updateConfiguration(conf, getResources().getDisplayMetrics());
Configuration systemConf = Resources.getSystem().getConfiguration();
updateConfiguration(systemConf, locale);
Resources.getSystem().updateConfiguration(conf, getResources().getDisplayMetrics());
Locale.setDefault(locale);
}
void updateConfiguration(Configuration conf, Locale locale) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
conf.setLocale(locale);
}else {
//noinspection deprecation
conf.locale = locale;
}
}
According to the source code of the DateUtils class it uses both Resource.getSystem() and Locale.getDefault() method for formatting date and time. You can change the default Locale using Locale.setDefault() method but I don't think it's possible to change the return value of the Resource.getSystem() method. You can try to change the default locale to Locale.US but it seems to me that results will be even worse in this case.