Android Get Current Locale, Not Default
Answer :
The default Locale
is constructed statically at runtime for your application process from the system property settings, so it will represent the Locale
selected on that device when the application was launched. Typically, this is fine, but it does mean that if the user changes their Locale
in settings after your application process is running, the value of getDefaultLocale()
probably will not be immediately updated.
If you need to trap events like this for some reason in your application, you might instead try obtaining the Locale
available from the resource Configuration
object, i.e.
Locale current = getResources().getConfiguration().locale;
You may find that this value is updated more quickly after a settings change if that is necessary for your application.
Android N (Api level 24) update (no warnings):
Locale getCurrentLocale(Context context){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){ return context.getResources().getConfiguration().getLocales().get(0); } else{ //noinspection deprecation return context.getResources().getConfiguration().locale; } }
If you are using the Android Support Library you can use ConfigurationCompat
instead of @Makalele's method to get rid of deprecation warnings:
Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);
or in Kotlin:
val currentLocale = ConfigurationCompat.getLocales(resources.configuration)[0]
Comments
Post a Comment