android 获取全国地址,android-如何获取国家(或其ISO代码)?

这是一个完整的例子。 尝试从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;

}

另外一个想法是尝试像此答案中那样的API请求,或使用精确的位置。

这里和这里的参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值