开发者

How do I get the country code of a user on Android?

开发者 https://www.devze.com 2023-04-01 02:27 出处:网络
How can I retrieve 开发者_开发百科a user\'s country code on Android? Do I need permissions?To get the country code stored in the sim card of the phone you can try

How can I retrieve 开发者_开发百科a user's country code on Android? Do I need permissions?


To get the country code stored in the sim card of the phone you can try

TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getSimCountryIso();

You can try also:

 Locale locale = Locale.getDefault();
 locale.getCountry();

This returns the data from the language/Country stated from the user and not the physical location.


Latitude and Longitude of the current location

Will get you the latitude and longitude.

I'd suggest using Google Map's reverse geocoding for getting the country, and then using a lookup table if you want to get some country code (I'd assume the country's telephone code, but I could be wrong).


Best practice from the: Localization documentation recommends using the Locale set here:

context.getResources().getConfiguration().locale;

Furthermore, this field is also mentioned here. You can then call getCountry() on it to obtain the two-letter uppercase ISO country code as defined by ISO 3166-1. Note that java doc says it may return an empty String if the Locale doesn't correspond to specific country.


You can try the following function. It's returning your country ISO code:

  TelephonyManager telephonyManager = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);

        public String getSimCountryIso() {

    return telephonyManager.getSimCountryIso();

}

Add permission below into your AndroidManifest.xml file.

 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号