切换系统语言时LOCALE_CHANGED接收器extras为null,如何获取新语言代码?
解决LOCALE_CHANGED广播无法通过Intent Extras获取切换后语言代码的问题
android.intent.action.LOCALE_CHANGED广播的Intent本身不会携带任何额外数据(extras),所以你拿到null是正常现象。要获取切换后的系统语言,需要直接从系统配置中读取当前Locale信息。
修改后的广播接收器代码
import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.LocaleList import android.widget.Toast import java.util.Locale class VzLocaleReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (context == null || intent?.action != "android.intent.action.LOCALE_CHANGED") { return } // 获取当前系统的Locale信息 val currentLocale: Locale = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { // Android N及以上支持多Locale,取首选Locale context.resources.configuration.locales[0] } else { @Suppress("DEPRECATION") // 低版本直接获取单个Locale context.resources.configuration.locale } // 获取语言代码(如"zh"、"en") val languageCode = currentLocale.language // 获取带地区的完整Locale代码(如"zh_CN"、"en_US") val fullLocaleCode = currentLocale.toString() Toast.makeText( context, "语言已切换:\n语言代码:$languageCode\n完整Locale:$fullLocaleCode", Toast.LENGTH_LONG ).show() } }
补充说明
- 你Manifest中的接收器配置无需修改,
android:exported="false"是安全的,系统发送的广播不受该属性限制,仍能正常接收。 - 如果你的应用单独设置了自定义语言(而非跟随系统),需要从应用自身的
Resources配置中读取Locale,而非系统全局配置。
内容的提问来源于stack exchange,提问作者Dalvendra Singh
相关产品推荐
相关产品推荐

