Android海外版app中,通常会同时支持多个国家,就会有选择国家的需求。为了提升用户体验,可以自动识别用户所在的国家,以简化交互。
下面代码的识别优先级依次为:SIM卡国家码、当前网络国家码、手机系统设置中的国家码。
import android.content.Context;
import android.content.res.Resources;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import androidx.core.os.ConfigurationCompat;
import androidx.core.os.LocaleListCompat;
public String getCountry() {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String country = tm.getSimCountryIso(); // SIM卡国家码
if (TextUtils.isEmpty(country)) {
country = tm.getNetworkCountryIso(); // 当前网络国家码
}
if (TextUtils.isEmpty(country)) {
country = getLocale().getCountry();
}
if (TextUtils.isEmpty(country)) {
country = "";
}
return country.toUpperCase();
}
// 此处获取系统的Locale对象,而非app中的Locale对象
public Locale getLocale() {
Locale locale;
try {
LocaleListCompat listCompat = ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration());
locale = listCompat.get(0);
} catch (Exception e) {
locale = Locale.getDefault();
}
return locale;
}
987

被折叠的 条评论
为什么被折叠?



