Android12.0 SIM卡语言自适应

2024-05-30 06:36
文章标签 语言 适应 sim android12.0

本文主要是介绍Android12.0 SIM卡语言自适应,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

        • 需求
        • 语言设定
        • Settings中语言切换流程
        • 检测到SIM卡,更新系统语言
        • 最终修改

需求

要求系统语言跟随SIM卡的语言变化。

语言设定

(1)系统预置语言, 即在makefile中指定的语言
(2)重启, 如果未插卡, 则系统语言为预置的语言
(3)重启插入SIM卡开机, 会自适应为SIM卡的语言
(4)如果有手动设置语言, 以后开机, 不管插入的是哪个国家的卡, 都会显示设置的语言, 不会根据SIM卡自适应变化.

Settings中语言切换流程

当在系统设置中手动设置语言拖拽结束后,会调用updateLocalesWhenAnimationStops(ll)方法

  • vendor/mediatek/proprietary/packages/apps/MtkSettings/src/com/android/settings/localepicker/LocaleDragAndDropAdapter.java
	public void updateLocalesWhenAnimationStops(final LocaleList localeList) {if (localeList.equals(mLocalesToSetNext)) {return;}// This will only update the Settings application to make things feel more responsive,// the system will be updated later, when animation stopped.LocaleList.setDefault(localeList);mLocalesToSetNext = localeList;final RecyclerView.ItemAnimator itemAnimator = mParentView.getItemAnimator();itemAnimator.isRunning(new RecyclerView.ItemAnimator.ItemAnimatorFinishedListener() {@Overridepublic void onAnimationsFinished() {if (mLocalesToSetNext == null || mLocalesToSetNext.equals(mLocalesSetLast)) {// All animations finished, but the locale list did not changereturn;}// 语言条目发生改变,调用到framework下的LocalePicker进行更新LocalePicker.updateLocales(mLocalesToSetNext);mLocalesSetLast = mLocalesToSetNext;new ShortcutsUpdateTask(mContext).execute();mLocalesToSetNext = null;mNumberFormatter = NumberFormat.getNumberInstance(Locale.getDefault());}});}

然后调用LocalePicker的updateLocales()方法进行更新

  • frameworks/base/core/java/com/android/internal/app/LocalePicker.java
    /*** Requests the system to update the list of system locales.* Note that the system looks halted for a while during the Locale migration,* so the caller need to take care of it.*/@UnsupportedAppUsagepublic static void updateLocales(LocaleList locales) {if (locales != null) {locales = removeExcludedLocales(locales);}// Note: the empty list case is covered by Configuration.setLocales().try {final IActivityManager am = ActivityManager.getService();final Configuration config = am.getConfiguration();// 切换后的语言信息更新到Configurationconfig.setLocales(locales);config.userSetLocale = true; // 手动设置的标志am.updatePersistentConfigurationWithAttribution(config,ActivityThread.currentOpPackageName(), null);// Trigger the dirty bit for the Settings Provider.BackupManager.dataChanged("com.android.providers.settings");} catch (RemoteException e) {// Intentionally left blank}}

又转入到ActivityManagerService中处理

  • frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
	@Overridepublic void updatePersistentConfigurationWithAttribution(Configuration values,String callingPackage, String callingAttributionTag) {enforceCallingPermission(CHANGE_CONFIGURATION, "updatePersistentConfiguration()");enforceWriteSettingsPermission("updatePersistentConfiguration()", callingPackage,callingAttributionTag);if (values == null) {throw new NullPointerException("Configuration must not be null");}int userId = UserHandle.getCallingUserId();// 这里的mActivityTaskManager就是ActivityTaskManagerServicemActivityTaskManager.updatePersistentConfiguration(values, userId);}

继续传递到ActivityTaskManagerService中处理updateConfigurationLocked()

  • frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
	public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {final long origId = Binder.clearCallingIdentity();try {synchronized (mGlobalLock) {// 配置发生改变(尺寸,字体),都会执行updateConfigurationLocked(values, null, false, true, userId,false /* deferResume */);}} finally {Binder.restoreCallingIdentity(origId);}}

在ActivityTaskManagerService内部经过一系列处理,最终执行到updateGlobalConfigurationLocked()

	int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,boolean persistent, int userId) {mTempConfig.setTo(getGlobalConfiguration());// 判断是否发生变化final int changes = mTempConfig.updateFrom(values);if (changes == 0) {return 0;}...if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {// 这里的locales包含所有已添加的语言,如果是第一次开机就是系统默认语言[en_US]final LocaleList locales = values.getLocales();int bestLocaleIndex = 0;if (locales.size() > 1) {if (mSupportedSystemLocales == null) {// 所有系统支持的语言mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();}bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));}// 如果是values.userSetLocale=true,设置系统属性SystemProperties.set("persist.sys.locale",locales.get(bestLocaleIndex).toLanguageTag());LocaleList.setDefault(locales, bestLocaleIndex);final Message m = PooledLambda.obtainMessage(ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,locales.get(bestLocaleIndex));mH.sendMessage(m);}mTempConfig.seq = increaseConfigurationSeqLocked();Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);...// Update stored global config and notify everyone about the change.mRootWindowContainer.onConfigurationChanged(mTempConfig); // 整个系统界面进行更新return changes;}
检测到SIM卡,更新系统语言

SIM卡ready后,会调用updateMccMncConfiguration()方法更新卡的MCC/MNC信息

  • frameworks/opt/telephony/src/java/com/android/internal/telephony/MccTable.java
 	/*** Updates MCC and MNC device configuration information for application retrieving* correct version of resources.  If MCC is 0, MCC and MNC will be ignored (not set).* @param context Context to act on.* @param mccmnc truncated imsi with just the MCC and MNC - MNC assumed to be from 4th to end*/public static void updateMccMncConfiguration(Context context, String mccmnc) {Rlog.d(LOG_TAG, "updateMccMncConfiguration mccmnc='" + mccmnc);if (TelephonyUtils.IS_DEBUGGABLE) {String overrideMcc = SystemProperties.get("persist.sys.override_mcc");if (!TextUtils.isEmpty(overrideMcc)) {mccmnc = overrideMcc;Rlog.d(LOG_TAG, "updateMccMncConfiguration overriding mccmnc='" + mccmnc + "'");}}if (!TextUtils.isEmpty(mccmnc)) {int mccInt;try {mccInt = Integer.parseInt(mccmnc.substring(0, 3));} catch (NumberFormatException | StringIndexOutOfBoundsException ex) {Rlog.e(LOG_TAG, "Error parsing mccmnc: " + mccmnc + ". ex=" + ex);return;}if (mccInt != 0) {ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);if (!activityManager.updateMccMncConfiguration(mccmnc.substring(0, 3), mccmnc.substring(3))) {Rlog.d(LOG_TAG, "updateMccMncConfiguration: update mccmnc="+ mccmnc + " failure");} else {Rlog.d(LOG_TAG, "updateMccMncConfiguration: update mccmnc="+ mccmnc + " success");}} else {Rlog.d(LOG_TAG, "updateMccMncConfiguration nothing to update");}}}

mcc参数不为0,继续往下执行到ActivityManagerService的updateMccMncConfiguration

  • frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
	@Overridepublic boolean updateConfiguration(Configuration values) {return mActivityTaskManager.updateConfiguration(values);}@Overridepublic boolean updateMccMncConfiguration(String mcc, String mnc) {int mccInt, mncInt;try {mccInt = Integer.parseInt(mcc);mncInt = Integer.parseInt(mnc);} catch (NumberFormatException | StringIndexOutOfBoundsException ex) {Slog.e(TAG, "Error parsing mcc: " + mcc + " mnc: " + mnc + ". ex=" + ex);return false;}Configuration config = new Configuration();config.mcc = mccInt;config.mnc = mncInt == 0 ? Configuration.MNC_ZERO : mncInt;return mActivityTaskManager.updateConfiguration(config);}

mcc/mnc参数没有问题更新Configuration,与Settings中设置语言一样执行到ActivityTaskManagerService中处理

  • frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
@Overridepublic boolean updateConfiguration(Configuration values) {mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");synchronized (mGlobalLock) {if (mWindowManager == null) {Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");return false;}if (values == null) {// sentinel: fetch the current configuration from the window managervalues = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);}mH.sendMessage(PooledLambda.obtainMessage(ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,DEFAULT_DISPLAY));final long origId = Binder.clearCallingIdentity();try {if (values != null) {Settings.System.clearConfiguration(values);}updateConfigurationLocked(values, null, false, false /* persistent */,UserHandle.USER_NULL, false /* deferResume */,mTmpUpdateConfigurationResult);return mTmpUpdateConfigurationResult.changes != 0;} finally {Binder.restoreCallingIdentity(origId);}}}

最终走updateConfigurationLocked(),与Settings中设置语言一样的流程。

最终修改
  • frameworks/opt/telephony/src/java/com/android/internal/telephony/MccTable.java
	// add for SIM language adaptiveimport android.content.res.Configuration;import android.os.LocaleList;import android.os.RemoteException;import android.app.ActivityManagerNative;// add end/*** Updates MCC and MNC device configuration information for application retrieving* correct version of resources.  If MCC is 0, MCC and MNC will be ignored (not set).* @param context Context to act on.* @param mccmnc truncated imsi with just the MCC and MNC - MNC assumed to be from 4th to end*/public static void updateMccMncConfiguration(Context context, String mccmnc) {Rlog.d(LOG_TAG, "updateMccMncConfiguration mccmnc='" + mccmnc);if (TelephonyUtils.IS_DEBUGGABLE) {String overrideMcc = SystemProperties.get("persist.sys.override_mcc");if (!TextUtils.isEmpty(overrideMcc)) {mccmnc = overrideMcc;Rlog.d(LOG_TAG, "updateMccMncConfiguration overriding mccmnc='" + mccmnc + "'");}}if (!TextUtils.isEmpty(mccmnc)) {int mccInt;int mncInt;try {mccInt = Integer.parseInt(mccmnc.substring(0, 3));// add for SIM language adaptivemncInt = Integer.parseInt(mccmnc.substring(3));// add end} catch (NumberFormatException | StringIndexOutOfBoundsException ex) {Rlog.e(LOG_TAG, "Error parsing mccmnc: " + mccmnc + ". ex=" + ex);return;}if (mccInt != 0) {// add for SIM language adaptivetry {Configuration config = new Configuration();config.mcc = mccInt;config.mnc = mncInt == 0 ? Configuration.MNC_ZERO : mncInt;// 根据MCC获取语言和国家码(对应的表是sTable)Locale mccLocale = LocaleUtils.getLocaleFromMcc(context, mccInt, null); // 根据sim卡的mcc参数获取的Locale不为空并且没有设置过语言,根据sim卡信息设置语言if (mccLocale != null && canUpdateLocale()){Configuration configLocal = new Configuration();configLocal = ActivityManagerNative.getDefault().getConfiguration();LocaleList userLocale = configLocal.getLocales();// sim卡语言置顶LocaleList newUserLocale = new LocaleList(mccLocale, userLocale);config.setLocales(newUserLocale);config.userSetLocale = true;config.fontScale = 1.0f;ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);if (!activityManager.updateConfiguration(config)) {Rlog.d(LOG_TAG, "updateConfiguration: update mccmnc="+ mccmnc + " failure");} else {Rlog.d(LOG_TAG, "updateConfiguration: update mccmnc="+ mccmnc + " success");}return;}} catch (RemoteException e) {throw e.rethrowFromSystemServer();}// add endActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);if (!activityManager.updateMccMncConfiguration(mccmnc.substring(0, 3), mccmnc.substring(3))) {Rlog.d(LOG_TAG, "updateMccMncConfiguration: update mccmnc="+ mccmnc + " failure");} else {Rlog.d(LOG_TAG, "updateMccMncConfiguration: update mccmnc="+ mccmnc + " success");}} else {Rlog.d(LOG_TAG, "updateMccMncConfiguration nothing to update");}}}// add for SIM language adaptiveprivate static boolean canUpdateLocale() {return !userHasPersistedLocale();}private static boolean userHasPersistedLocale() {String persistSysLanguage = SystemProperties.get("persist.sys.locale", "");return !(persistSysLanguage.isEmpty());}// add end
  • frameworks/base/core/java/android/app/ActivityManager.java
	import android.content.res.Configuration;// add for SIM language adaptivepublic boolean updateConfiguration(@NonNull Configuration values) {try {return getService().updateConfiguration(values);} catch (RemoteException e) {throw e.rethrowFromSystemServer();}}// add end

修改完之后
(1)系统预置语言, 即在makefile中指定的语言
(2)重启, 如果未插卡, 则系统语言为预置的语言
(3)重启插入SIM卡开机, 会自适应为SIM卡的语言
(4)如果有手动设置语言, 以后开机, 不管插入的是哪个国家的卡, 都会显示设置的语言, 不会根据SIM卡自适应变化.

这篇关于Android12.0 SIM卡语言自适应的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1015830

相关文章

Go语言中make和new的区别及说明

《Go语言中make和new的区别及说明》:本文主要介绍Go语言中make和new的区别及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1 概述2 new 函数2.1 功能2.2 语法2.3 初始化案例3 make 函数3.1 功能3.2 语法3.3 初始化

Go语言中nil判断的注意事项(最新推荐)

《Go语言中nil判断的注意事项(最新推荐)》本文给大家介绍Go语言中nil判断的注意事项,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1.接口变量的特殊行为2.nil的合法类型3.nil值的实用行为4.自定义类型与nil5.反射判断nil6.函数返回的

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

Go语言代码格式化的技巧分享

《Go语言代码格式化的技巧分享》在Go语言的开发过程中,代码格式化是一个看似细微却至关重要的环节,良好的代码格式化不仅能提升代码的可读性,还能促进团队协作,减少因代码风格差异引发的问题,Go在代码格式... 目录一、Go 语言代码格式化的重要性二、Go 语言代码格式化工具:gofmt 与 go fmt(一)

Go语言中泄漏缓冲区的问题解决

《Go语言中泄漏缓冲区的问题解决》缓冲区是一种常见的数据结构,常被用于在不同的并发单元之间传递数据,然而,若缓冲区使用不当,就可能引发泄漏缓冲区问题,本文就来介绍一下问题的解决,感兴趣的可以了解一下... 目录引言泄漏缓冲区的基本概念代码示例:泄漏缓冲区的产生项目场景:Web 服务器中的请求缓冲场景描述代码

Go语言如何判断两张图片的相似度

《Go语言如何判断两张图片的相似度》这篇文章主要为大家详细介绍了Go语言如何中实现判断两张图片的相似度的两种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 在介绍技术细节前,我们先来看看图片对比在哪些场景下可以用得到:图片去重:自动删除重复图片,为存储空间"瘦身"。想象你是一个

Go语言中Recover机制的使用

《Go语言中Recover机制的使用》Go语言的recover机制通过defer函数捕获panic,实现异常恢复与程序稳定性,具有一定的参考价值,感兴趣的可以了解一下... 目录引言Recover 的基本概念基本代码示例简单的 Recover 示例嵌套函数中的 Recover项目场景中的应用Web 服务器中

Go语言中使用JWT进行身份验证的几种方式

《Go语言中使用JWT进行身份验证的几种方式》本文主要介绍了Go语言中使用JWT进行身份验证的几种方式,包括dgrijalva/jwt-go、golang-jwt/jwt、lestrrat-go/jw... 目录简介1. github.com/dgrijalva/jwt-go安装:使用示例:解释:2. gi

Go 语言中的 Struct Tag 的用法详解

《Go语言中的StructTag的用法详解》在Go语言中,结构体字段标签(StructTag)是一种用于给字段添加元信息(metadata)的机制,常用于序列化(如JSON、XML)、ORM映... 目录一、结构体标签的基本语法二、json:"token"的具体含义三、常见的标签格式变体四、使用示例五、使用

Go语言使用slices包轻松实现排序功能

《Go语言使用slices包轻松实现排序功能》在Go语言开发中,对数据进行排序是常见的需求,Go1.18版本引入的slices包提供了简洁高效的排序解决方案,支持内置类型和用户自定义类型的排序操作,本... 目录一、内置类型排序:字符串与整数的应用1. 字符串切片排序2. 整数切片排序二、检查切片排序状态: