java 如何在 Android 上获取用户的国家/地区代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7251861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:17:20  来源:igfitidea点击:

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

javaandroidlocalizationgeolocation

提问by Caroline

How can I retrieve a user's country code on Android? Do I need permissions?

如何在 Android 上检索用户的国家/地区代码?我需要权限吗?

回答by weakwire

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

要获取存储在手机 SIM 卡中的国家代码,您可以尝试

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.

这将返回来自用户声明的语言/国家/地区的数据,而不是物理位置。

回答by Caroline

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).

我建议使用 Google Map 的反向地理编码来获取国家/地区,然后如果您想获得一些国家/地区代码,则使用查找表(我假设该国家/地区的电话代码,但我可能是错误的)。

回答by fr1550n

Best practice from the: Localization documentationrecommends 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. Notethat java doc says it may return an empty String if the Locale doesn't correspond to specific country.

此外,这里也提到这个字段。然后,您可以对其调用 getCountry() 以获取 ISO 3166-1 定义的两个字母的大写 ISO 国家/地区代码。 请注意,java doc 说如果语言环境与特定国家/地区不对应,它可能会返回一个空字符串。

回答by Quantum4U

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

您可以尝试以下功能。它正在返回您所在国家/地区的 ISO 代码:

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

        public String getSimCountryIso() {

    return telephonyManager.getSimCountryIso();

}

Add permission below into your AndroidManifest.xmlfile.

在您的AndroidManifest.xml文件中添加以下权限。

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