2016-08-01 211 views
0

我试图获取手机所在的国家/地区名称。例如,如果用户在德国,则必须说德国。我尝试了几件事情来实现这一点,但我还没有找到任何适当的解决方案。我知道我可以使用TelephonyManager,但那会给我ISO,我想要国家的名字。我也试过这个getApplicationContext().getResources().getConfiguration().locale.getDisplayCountry();,但即使我不在那里,它总是给我“美国”。我知道这是可能的,因为我已经在另一个应用程序中看到它。我应该以某种方式使用ISO来实现我的目标,还是有更智能/更简单的方法?获取当前国家/地区名称

请,因为我已经在这里搜索#2不投这个职位的重复,但没有任何解决方案,使该国:)

+0

请参阅:http://stackoverflow.com/questions/3659809/where-am-i-get-country –

+0

我已经看过那篇文章,但是收到的国家名?大多数解决方案是如何获得ISO。 –

+0

ISO是一个相对静态的列表,只需将其添加到您的应用程序并查找全名即可。 –

回答

0

Where am I? - Get country 的名字给这个代码

/** 
* 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; 
} 
+0

嗯,这不会太“深”吗?我的意思是拿到国名。我不能使用ISO获取名称吗? 'getApplicationContext()。getResources()。getConfiguration()。locale.getDisplayCountry();'给了我“美国”,我只是想让它正常工作(如果可能的话) –

+0

是否正在测试'getApplicationContext()。getResources ).getConfiguration()。locale.getDisplayCoun try();'在android模拟器或实际的手机上? –

+0

已经尝试 –

相关问题