如何获取设备的当前地区?
假设用户在德国并使用意大利语作为设备语言。
如果使用Locale.getDefault()
,则国家和语言将被映射到一起,即语言为it,国家为IT。我想要的是it和DE/GR(无论是德国还是希腊的国家代码)。
并非所有的本地化国家(组合)都被Android支持,这就是为什么您现在无法以您目前的方式获取国家。
您可以使用不同的方法来获取国家代码。例如,请参阅:我在哪里?- 获取国家
第二个答案展示了对您有用的代码:(感谢@Marco W.)
/**
* 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;
}