I’m trying to get the country language of the user, not the selected one on the phone.
For example:
I’m building an English learning app, but in my phone I’ve set language to English for learning purposes, and it doesn’t translate because it thinks that my language is English, but I live in brazil, I want it to find that my language is Portuguese. to get languages by especific location.
I have tried some codes, but not seems to work.
I have many users in my app that have English language on phone, so they are facing the same problem.
var currentLanguage: String = Locale.getDefault().language
var language = this.getResources().getConfiguration().getLocales().get(0).language
They both give me the same value, that my language is english, and if I get the country it says I’m in US.
EDIT:
I’m able to get the country code with it:
var tm = this.getSystemService(TELEPHONY_SERVICE) as TelephonyManager
var countryCodeValue = tm.networkCountryIso
It returns br, but how can I get the language from this tag?
There is something like:
countryCodeValue.language
?
2
Answers
Well guys, I did it, and its working almost as I wanted it to be. I'll have a little work to do it for too much countries. If someone have a better Idea, I'd be glad to know. Thanks. Maybe it can help someone.
Well you have it there in your own description of the problem. You want to get the language based on the country the user is in. So you need to first get the country where the user is in. So it’s a location problem.
There are several options. One is to get the user’s location using the last known location of the user.
Docs: https://developer.android.com/training/location/retrieve-current
The problem here is you need to then transform coordinates to country. There are some API’s for this, Google maps has one.
Maybe an easier approach is to use the TelephonyManager to get the country code of the user. This also has a problem because it relies on having a sim card.
Finally you need to transform that country to a language. But you can do that with the Locale class.
IMHO, it would be easier to give your users a selector for the language, that way they can decide what language to use instead of you choosing for them based on some algorithm.
Update:
It’s not that straight forward to get the language of a Country. Basically some countries have multiple official languages for example. There are other questions addressing this issue. But in short, you either have a static file mapping from country to language or you iterate over the available Locales and choose one of the languages for the country.
Here are other questions: