Android 如何获取国家(或其 ISO 代码)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12210696/
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-08-20 10:01:26  来源:igfitidea点击:

How to get Country (or its ISO code)?

androidlocationcountry-codes

提问by Vishal Pawar

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.

获取国家代码的最佳方法是什么?截至目前,我知道两种方法,一种是通过 TelephonyManager 获取,另一种是通过 Locale 获取,这是在 android 中查找国家/地区代码的另一种最佳且独特的方法。

采纳答案by Vishal Pawar

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.

我通过IP地址解决了它。您可以获得手机的IP地址。如果您使用的是 wifi,那么它将是 wifi 热点的 IP 地址或您的移动服务提供服务器的 IP,因此您可以从该 IP 发送到 Web 服务或跟踪该 IP 地址的国家/地区的某些资源(数据库),如果互联网可用这里提供 IP 国家的例子是http://whatismyipaddress.com/ip-lookup

回答by Sahil Mahajan Mj

Try this,

尝试这个,

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
      String countryCode = tm.getSimCountryIso();

回答by Jose L Ugia

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.

选择非常简单:使用 Locale(获取用户选择的首选语言),或者尽最大努力以他们已经说过不想看到的语言向他们展示信息来激怒他们。

To get the country code use:

要获取国家代码,请使用:

Locale.getDefault().getCountry();

回答by Asaf Pinhassi

            TelephonyManager tm = (TelephonyManager)getSystemService(getApplicationContext().TELEPHONY_SERVICE);
          String countryCode = tm.getNetworkCountryIso();

It is better than getSimCountryIsobecause getSimCountryIsodepends on the operator to burn the country iso on the SIM and it also supports CDMA networks.

这比getSimCountryIso因为getSimCountryIso依赖运营商在 SIM 上烧国家 iso更好,而且它还支持 CDMA 网络。

回答by Bach Vu

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

您可以使用此代码获取 ISO2: Locale.getDefault().getCountry()

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

这是为了获得 ISO3: Locale.getDefault().getISO3Country()

Hope this helps

希望这可以帮助

回答by D4rWiNS

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

我认为 ip 是最好的方式,因为它会给你现在电话所在的国家,

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

该用户将无法购买您的产品,因此 ip 是我认为的最佳方式

回答by HitOdessit

There is an excellent article by Reto Meier: http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html

Reto Meier 有一篇很棒的文章:http: //android-developers.blogspot.com/2011/06/deep-dive-into-location.html

It describes different techniques to get location of an android device, including source code. Next, when you have location, it's easy to get country for it - use can use online web-serviceor offline database

它描述了获取 android 设备位置的不同技术,包括源代码。接下来,当你有位置时,很容易找到它的国家 - 使用可以使用在线网络服务离线数据库

回答by sunil sunny

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). TelephonyManagerwon't work if there is no SIM in your phone.

如果没有 GPS 和谷歌服务(中国),很难找到这个国家。TelephonyManager如果您的手机中没有 SIM 卡,则无法使用。

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

Locale中国如果用户设置自己的语言为英语(你会得到将是美国或英国的国家)将无法正常工作。

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

如果您的应用程序需要互联网连接,那么有一个选项。您可以使用这个名为ip-api 的 API。如果您打算使用它,请先阅读那里的文档

There are other APIs like this freegeoip api

还有其他的 API,比如这个freegeoip api

回答by radu_paun

Here is a complete example. Try to get country code from TelephonyManager (from SIM or CDMA devices), and if not available try to get it from local configuration.

这是一个完整的例子。尝试从 TelephonyManager(从 SIM 或 CDMA 设备)获取国家代码,如果不可用,请尝试从本地配置获取。

private static String getDeviceCountryCode(Context context) {
    String countryCode;

    // try to get country code from TelephonyManager service
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    if(tm != null) {
        // query first getSimCountryIso()
        countryCode = tm.getSimCountryIso();
        if (countryCode != null && countryCode.length() == 2)
            return countryCode.toLowerCase();

        if (tm.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
            // special case for CDMA Devices
            countryCode = getCDMACountryIso();
        } else {
            // for 3G devices (with SIM) query getNetworkCountryIso()
            countryCode = tm.getNetworkCountryIso();
        }

        if (countryCode != null && countryCode.length() == 2)
            return countryCode.toLowerCase();
    }

    // if network country not available (tablets maybe), get country code from Locale class
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        countryCode = context.getResources().getConfiguration().getLocales().get(0).getCountry();
    } else {
        countryCode = context.getResources().getConfiguration().locale.getCountry();
    }

    if (countryCode != null && countryCode.length() == 2)
        return  countryCode.toLowerCase();

    // general fallback to "us"
    return "us";
}

@SuppressLint("PrivateApi")
private static String getCDMACountryIso() {
    try {
        // try to get country code from SystemProperties private class
        Class<?> systemProperties = Class.forName("android.os.SystemProperties");
        Method get = systemProperties.getMethod("get", String.class);

        // get homeOperator that contain MCC + MNC
        String homeOperator = ((String) get.invoke(systemProperties,
                "ro.cdma.home.operator.numeric"));

        // first 3 chars (MCC) from homeOperator represents the country code
        int mcc = Integer.parseInt(homeOperator.substring(0, 3));

        // mapping just countries that actually use CDMA networks
        switch (mcc) {
            case 330: return "PR";
            case 310: return "US";
            case 311: return "US";
            case 312: return "US";
            case 316: return "US";
            case 283: return "AM";
            case 460: return "CN";
            case 455: return "MO";
            case 414: return "MM";
            case 619: return "SL";
            case 450: return "KR";
            case 634: return "SD";
            case 434: return "UZ";
            case 232: return "AT";
            case 204: return "NL";
            case 262: return "DE";
            case 247: return "LV";
            case 255: return "UA";
        }
    } catch (ClassNotFoundException ignored) {
    } catch (NoSuchMethodException ignored) {
    } catch (IllegalAccessException ignored) {
    } catch (InvocationTargetException ignored) {
    } catch (NullPointerException ignored) {
    }

    return null;
}

Also another idea is to try an API request like in this answer, or to use fine location.

另一个想法是尝试像这个答案中的 API 请求,或者使用精细的位置

References hereand here

参考这里这里