What is the best way to get the country code?
As of now, I know two ways. One is to get by TelephonyManager and another by Locale. Which is another best and unique wa
I solved it by IP Address. You can get the IP address of your phone. If you are using Wi-Fi then it will be the IP address of the Wi-Fi hotspot or IP address of your mobile service provider server, so from that IP address you can send to a web service or something to track the country of that IP address.
There are some sources (database) available if Internet which provides the country of IP address.
Here is the example http://whatismyipaddress.com/ip-lookup.
Use:
TelephonyManager tm = (TelephonyManager)getSystemService(getApplicationContext().TELEPHONY_SERVICE);
String countryCode = tm.getNetworkCountryIso();
It is better than getSimCountryIso
because getSimCountryIso
depends on the operator to burn the country ISO into the SIM and it also supports CDMA networks.
There are always huge discussions about this, and I never understand why developers and companies go for the complex way. The language selected by the user, means the language he/she wants to see always in his/her phone. They don't intend to have apps in a different language than others or the system.
The choice is very straight forward: Use Locale (to get the language the user selected as preferred), or make your best to piss them off showing them information in a language they already said they don't want to see things in.
To get the country code use:
Locale.getDefault().getCountry();
You can use this code to get ISO 2:
Locale.getDefault().getCountry()
And this to get ISO 3:
Locale.getDefault().getISO3Country()
I think the IP address is the best way because it will give you the country where the phone is at the moment.
If you do it by
Locale.getDefault().getCountry();
you get the country where the user select the country, so you can have selected England, and you can be in Spain and maybe you need to know where he/she is at the moment.
Example: imagine that your app can buy something only in England. The user is from Spain, but he/she is on holidays in England and he/she wants to buy your product ... if you use
Locale.getDefault().getCountry();
that user won't be able to buy your product, so the IP address is the best way I think.
It's very hard to find the country without GPS and Google Services (China). TelephonyManager
won't work if there isn't any SIM card in your phone.
And Locale
won't work if a user in China set his/her language as English (the country you will be getting will be US or UK).
If your app requires an Internet connection then there is an option. You could use this API called ip-api. Please go through their documentation first if you are planing to use this.
There are other APIs like this freegeoip API.