繁体   English   中英

获取当前的国家名称

[英]Getting current country name

我正在尝试获取电话所在的国家/地区名称。例如,如果用户在德国,则必须说出德国。 我已经尝试了几种方法来实现这一目标,但是我还没有找到任何合适的解决方案。 我知道我可以使用TelephonyManager ,但这将为我提供ISO,并且我想要国家的名称。 我也尝试过这个getApplicationContext().getResources().getConfiguration().locale.getDisplayCountry(); ,但即使我不在那也总是给我“美国”。 我知道这是可能的,因为我已经在另一个应用程序中看到了。 我应该以某种方式使用ISO完成我所要做的事情,还是有一种更聪明/更简便的方法?

请不要将这篇文章投重复,因为我已经在Stackoverflow上进行了搜索,但是没有任何解决方案来获取国家名称:)

我在哪里? -获取国家/地区提供此代码

/**
 * Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
 * @param context Context reference to get the TelephonyManager instance from
 * @return country code or null
 */
public static String getUserCountry(Context context) {
    try {
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final String simCountry = tm.getSimCountryIso();
        if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
            return simCountry.toLowerCase(Locale.US);
        }
        else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
            String networkCountry = tm.getNetworkCountryIso();
            if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
                return networkCountry.toLowerCase(Locale.US);
            }
        }
    }
    catch (Exception e) { }
    return null;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM