How to get the current locale (API level 24)?

user3290180 picture user3290180 · Jul 8, 2016 · Viewed 15.7k times · Source

I was doing this way:

context.getResources().getConfiguration().locale

Configuration.locale is deprecated if target is 24. So I made this change:

context.getResources().getConfiguration().getLocales().get(0)

Now it says that it's only for minSdkVersion 24, so I cannot use it because my min target is lower.

What's the right method?

Answer

Egor picture Egor · Jul 8, 2016

Check which version you're running on and fallback to the deprecated solution:

Locale locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    locale = context.getResources().getConfiguration().getLocales().get(0);
} else {
    locale = context.getResources().getConfiguration().locale;
}