You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编程获取Android设备的系统区域设置信息

获取Android系统设置区域国家码的正确方式

你当前使用的读取Resources.getSystem().getConfiguration()中Locale的方案,在Android 7.0以上部分版本、以及语言和区域分离设置的ROM上,可能和用户实际在系统设置中选择的区域值不一致,以下是全版本适配的可靠实现:

实现逻辑说明

不同Android版本的区域设置存储逻辑有差异,需要分版本适配:

  • Android 12(API 31)及以上:使用系统官方提供的LocaleManager服务,直接读取系统级的默认区域配置,不受应用自身配置影响
  • Android 7.0(API 24)~ Android 11(API 30):从系统全局设置表中读取用户配置的系统区域列表,取首项即为用户设置的默认区域
  • Android 7.0(API 24)以下:系统语言和区域为绑定设置,原有读取系统Configuration的逻辑取值准确

完整实现代码

public static String getDeviceSettingCountryCode(Context context) {
    String countryCode = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        LocaleManager localeManager = context.getSystemService(LocaleManager.class);
        if (localeManager != null) {
            LocaleList systemLocales = localeManager.getSystemLocales();
            if (!systemLocales.isEmpty()) {
                countryCode = systemLocales.get(0).getCountry();
            }
        }
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        String localeTags = Settings.Global.getString(
                context.getContentResolver(),
                Settings.Global.SYSTEM_LOCALES
        );
        if (!TextUtils.isEmpty(localeTags)) {
            LocaleList localeList = LocaleList.forLanguageTags(localeTags);
            if (!localeList.isEmpty()) {
                countryCode = localeList.get(0).getCountry();
            }
        }
        // 兜底逻辑
        if (TextUtils.isEmpty(countryCode)) {
            countryCode = Resources.getSystem().getConfiguration().getLocales().get(0).getCountry();
        }
    } else {
        countryCode = Resources.getSystem().getConfiguration().locale.getCountry();
    }

    // 校验国家码格式,不符合则返回默认值
    if (!TextUtils.isEmpty(countryCode) && countryCode.length() == 2) {
        return countryCode.toLowerCase(Locale.US);
    }
    return "us";
}

注意事项

  • 调用方法时请传入Application上下文,不要传入Activity上下文避免内存泄漏
  • 不要使用context.getResources().getConfiguration()读取区域值,该取值会受应用自身多语言配置、资源替换等逻辑影响,无法保证和系统设置值一致
  • 若需要覆盖极端定制ROM的场景,可以额外增加SIM卡ISO国家码、移动网络注册国家码作为兜底,但上述实现已经覆盖所有官方AOSP版本和国内主流定制ROM的系统设置区域取值逻辑

内容的提问来源于stack exchange,提问作者TNT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 18:22:48