android手机实际上非常清楚它在哪里--但是有没有一种方法可以通过国家代码之类的东西来检索国家呢?
不需要知道确切的GPS位置-国家就足够了。
我首先想到的是使用时区,但实际上我需要更多的信息,因为无论地点是纽约还是利马,这都是有区别的。
问题的背景:我有一个使用温度值的应用程序,我想根据位置是美国还是国外,将默认单位设置为摄氏度或华氏度
发布于 2013-10-17 06:48:48
/**
* 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;
}
发布于 2010-09-08 00:23:05
实际上,我刚刚发现还有一种获取国家代码的方法,那就是使用TelephoneManager
的getSimCountryIso()方法
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();
因为它是sim代码,所以在旅行到其他国家时也不应该改变。
发布于 2010-09-07 23:00:59
首先,获取LocationManager。然后,调用LocationManager.getLastKnownPosition
。然后创建一个GeoCoder并调用GeoCoder.getFromLocation
。这是在一个单独的线程中完成的!这将为您提供一个Address
对象列表。给Address.getCountryName
打电话,你就能搞定了。
请记住,最后已知的位置可能有点陈旧,因此如果用户刚刚越过边界,您可能会在一段时间内不知道它。
https://stackoverflow.com/questions/3659809
复制相似问题