How to get Country (or its ISO code)?

2019-01-13 07:47发布

What is the best way to get country code? As of now I know two ways one is to get by TelephonyManager and another by Locale which is the other best & unique way to find country code in android.

9条回答
对你真心纯属浪费
2楼-- · 2019-01-13 07:51

I know it's a very old question but I think this will help some of devs:

It's very hard to find the country without GPS and Google Services (China). TelephonyManager won't work if there is no SIM in your phone.

And Locale won't work if a user in China set his language as English (the country you will be getting will be US or UK).

If your app requires internet connection then there is an option. You could use this API called ip-api. Please go through there documentation first if you are planing to use this

There are other APIs like this freegeoip api

查看更多
叼着烟拽天下
3楼-- · 2019-01-13 07:57

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();
查看更多
Lonely孤独者°
4楼-- · 2019-01-13 07:58

I think ip is the best way because it will give you the country where the phone is at the momment,

If you do it by

    Locale.getDefault().getCountry();,

you got 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 is him at the momment

Example: imagine that your app can buy something ONLY in england, the user is from Spain but he is on holidays on England and he want to buy your product ... if you use

    Locale.getDefault().getCountry(); 

that user wont be able to buy your product,so the ip is the best way i think

查看更多
Rolldiameter
5楼-- · 2019-01-13 08:00

I solved it by IP Address. You can get IP Address of your phone. If you are using wifi then it will IP address of wifi hotspot or IP of your Mobile Service Provide server so from that IP you can send to web service or something to track country of that IP Address there are some sources(database) available if internet which provides country of IP here is the example http://whatismyipaddress.com/ip-lookup.

查看更多
爷、活的狠高调
6楼-- · 2019-01-13 08:07

You can use this code to get ISO2: Locale.getDefault().getCountry()

And this to get ISO3: Locale.getDefault().getISO3Country()

Hope this helps

查看更多
叛逆
7楼-- · 2019-01-13 08:08

Try this,

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
      String countryCode = tm.getSimCountryIso();
查看更多
登录 后发表回答