Android中如何根据国家代码获取对应货币?
根据两位字母国家代码获取对应货币(无需额外运行时权限)
完全可以基于你拿到的两位字母国家代码获取对应货币,且不需要新增任何运行时权限,实现方法如下:
核心实现思路
利用Android系统内置的Locale和Currency类,通过国家代码构建区域实例,再直接获取对应货币信息,全程无需额外权限。
补充后的完整代码
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); final String simCountry = tm.getSimCountryIso(); if (simCountry != null && simCountry.length() == 2) { // SIM国家代码可用 String countryCode = simCountry.toUpperCase(Locale.US); // 构建对应国家的Locale实例 Locale countryLocale = new Locale("", countryCode); // 获取该国家默认的货币 Currency currency = Currency.getInstance(countryLocale); // 按需获取货币的各类信息 String currencyCode = currency.getCurrencyCode(); // 示例:印度返回 "INR" String currencySymbol = currency.getSymbol(countryLocale); // 示例:印度返回 "₹" int decimalDigits = currency.getDefaultFractionDigits(); // 示例:印度返回 2 }
关键注意事项
- 必须将国家代码转换为大写格式,因为
Locale的构造要求符合ISO 3166-1 alpha-2的标准格式 Currency.getInstance()方法仅依赖系统内置的区域数据库,不需要申请任何运行时权限- 若某国家存在多种官方货币,系统会返回该国家默认的主流货币
内容的提问来源于stack exchange,提问作者Mukesh Roy
相关产品推荐
相关产品推荐

