How to Get the IETF BCP47 Language Code in Android API < 21
Before Android API level 21, there was no built-in way to directly obtain the IETF BCP47 language code (e.g., “en-US”). This article explains how to retrieve it in older Android versions.
The Challenge
Prior to API 21, Android provided the following methods to access language information:
Locale.getDefault()
: This returned the system’s default locale, but only provided the language code (e.g., “en”) and optionally a country code (e.g., “US”).Locale.getLanguage()
: This retrieved only the language code, not the entire BCP47 tag.Locale.getCountry()
: This retrieved only the country code, not the entire BCP47 tag.
Solutions
Here’s how to overcome this limitation and obtain the IETF BCP47 language code in API levels below 21:
1. Manual Concatenation
The most straightforward approach is to manually concatenate the language and country codes:
Locale locale = Locale.getDefault(); String languageCode = locale.getLanguage(); String countryCode = locale.getCountry(); String bcp47Tag = languageCode + "-" + countryCode;
// Example Output: en-US
2. Using the `Locale.toLanguageTag()` method
Android introduced the Locale.toLanguageTag()
method in API level 21 to get the BCP47 language tag. To use it in older versions, you can implement your own version of this method:
public static String toLanguageTag(Locale locale) { if (locale == null) { return ""; } String languageCode = locale.getLanguage(); String countryCode = locale.getCountry(); return languageCode + (countryCode.isEmpty() ? "" : "-" + countryCode); }
// Usage: Locale locale = Locale.getDefault(); String bcp47Tag = toLanguageTag(locale);
// Example Output: en-US
Comparison
Method | API Level | Availability |
---|---|---|
Manual Concatenation | All | Always available, but requires manual coding. |
Locale.toLanguageTag() |
>= 21 | Built-in method, but not available in older API levels. |
Choosing the Best Solution
- If targeting API levels below 21, manual concatenation is the only option.
- For API levels 21 and above, use the built-in
Locale.toLanguageTag()
method. - The custom
toLanguageTag()
implementation provides compatibility across API levels.
Note
Remember that this approach only provides the basic language and country code information. For more complex scenarios involving script, region, variant, and other BCP47 components, you’ll need to implement more sophisticated logic.