網(wǎng)站首頁 編程語言 正文
快速定位與修復(fù)
修改記錄 | 修改時間 |
---|---|
新建 | 2021.01.09 |
出現(xiàn)問題時的調(diào)用方式:
public class I18nBaseActivity extends AppCompatActivity { @Override protected void attachBaseContext(Context newBase) { //切換多語言,然后將新生成的 context 覆蓋給 attachBaseContext() Context context = MultiLanguageUtils.changeContextLocale(newBase); super.attachBaseContext(context); } }
解決方法:
Androidx(appcompat:1.2.0) 中對attachBaseContext()
包裝了一層ContextThemeWrapper
,但就是因為他給包的這一層邏輯有問題,導(dǎo)致了多語言切換時效。所以咱們手動給包一層
public class I18nBaseActivity extends AppCompatActivity { @Override protected void attachBaseContext(Context newBase) { //切換多語言,然后將新生成的 context 覆蓋給 attachBaseContext() Context context = MultiLanguageUtils.changeContextLocale(newBase); //兼容appcompat 1.2.0后切換語言失效問題 final Configuration configuration = context.getResources().getConfiguration(); final ContextThemeWrapper wrappedContext = new ContextThemeWrapper(context, R.style.Base_Theme_AppCompat_Empty) { @Override public void applyOverrideConfiguration(Configuration overrideConfiguration) { if (overrideConfiguration != null) { overrideConfiguration.setTo(configuration); } super.applyOverrideConfiguration(overrideConfiguration); } }; super.attachBaseContext(wrappedContext); } }
封裝
上面僅說明了怎么解決問題,沒有體現(xiàn)多語言切換的實現(xiàn)。所以我封裝了一個庫(實質(zhì)就是一個工具類),該庫已經(jīng)適配了該問題,大家可以直接copy出來使用
Github : github.com/StefanShan/…
詳細排查過程與原理
最近項目升級為 Androidx,發(fā)現(xiàn)之前的多語言切換失效了。經(jīng)過一點點排除方式排查,發(fā)現(xiàn)是由于升到 Androidx 后項目引入了 androidx.appcompat:appcompat:1.2.0
來替代之前的v7
包。那么根據(jù)多語言切換原理來看看是什么原因。
多語言切換原理:修改 context 的 Locale 配置,將新生成的 context 設(shè)置給 attachBaseContext 實現(xiàn)配置的替換。
先來看下 androidx 下的 AppCompatActivity# attachBaseContext() 源碼
@Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(getDelegate().attachBaseContext2(newBase)); }
哦~ 有個代理類處理了傳入的 context,看下這個代理類 getDelegate()
的attachBaseContext2()
/** * @return The {@link AppCompatDelegate} being used by this Activity. */ @NonNull public AppCompatDelegate getDelegate() { if (mDelegate == null) { mDelegate = AppCompatDelegate.create(this, this); //代理對象是通過 AppCompatDelegate create出來的,那繼續(xù)往下看 } return mDelegate; }
// 這里直接看 AppCompatDelegateImpl 類,該類是 AppCompatDelegate 類的實現(xiàn)類 @NonNull @Override @CallSuper public Context attachBaseContext2(@NonNull final Context baseContext) { //...... /** * 這段邏輯是:如果傳入的 context 是經(jīng)過 ContextThemeWrapper 封裝的,則直接使用該 context 配置進行覆蓋 */ // If the base context is a ContextThemeWrapper (thus not an Application context) // and nobody's touched its Resources yet, we can shortcut and directly apply our // override configuration. if (sCanApplyOverrideConfiguration && baseContext instanceof android.view.ContextThemeWrapper) { final Configuration config = createOverrideConfigurationForDayNight( baseContext, modeToApply, null); if (DEBUG) { Log.d(TAG, String.format("Attempting to apply config to base context: %s", config.toString())); } try { ContextThemeWrapperCompatApi17Impl.applyOverrideConfiguration( (android.view.ContextThemeWrapper) baseContext, config); return baseContext; } catch (IllegalStateException e) { if (DEBUG) { Log.d(TAG, "Failed to apply configuration to base context", e); } } } // ...... /** * 下面這段邏輯是:通過 packageManger 獲取配置,然后和傳入的 context 配置進行對比,覆蓋修改過的配置。 * 這里有個關(guān)鍵因素,通過 packageManager 獲取的配置與 context 的配置進行 diff 更新,并將 diff 結(jié)果賦值給新建的 configration。這就會導(dǎo)致,當(dāng)這一次切換成功后,殺死進程下次啟動時,由于 packageManager 配置的語言 與 context 配置的語言一致,而直接跳過,并沒有給新建的 configration進行賦值。最終導(dǎo)致多語言切換失效。同理,從 ActivityA 設(shè)置了多語言,然后重啟 ActivityA,再從ActivityA 跳轉(zhuǎn)到 ActivityB,此時ActivityB 多語言并沒有生效。 */ // We can't trust the application resources returned from the base context, since they // may have been altered by the caller, so instead we'll obtain them directly from the // Package Manager. final Configuration appConfig; try { appConfig = baseContext.getPackageManager().getResourcesForApplication( baseContext.getApplicationInfo()).getConfiguration(); } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException("Application failed to obtain resources from itself", e); } // The caller may have directly modified the base configuration, so we'll defensively // re-structure their changes as a configuration overlay and merge them with our own // night mode changes. Diffing against the application configuration reveals any changes. final Configuration baseConfig = baseContext.getResources().getConfiguration(); final Configuration configOverlay; if (!appConfig.equals(baseConfig)) { configOverlay = generateConfigDelta(appConfig, baseConfig); //這里是關(guān)鍵 if (DEBUG) { Log.d(TAG, "Application config (" + appConfig + ") does not match base config (" + baseConfig + "), using base overlay: " + configOverlay); } } else { configOverlay = null; if (DEBUG) { Log.d(TAG, "Application config (" + appConfig + ") matches base context " + "config, using empty base overlay"); } } final Configuration config = createOverrideConfigurationForDayNight( baseContext, modeToApply, configOverlay); if (DEBUG) { Log.d(TAG, String.format("Applying night mode using ContextThemeWrapper and " + "applyOverrideConfiguration(). Config: %s", config.toString())); } // Next, we'll wrap the base context to ensure any method overrides or themes are left // intact. Since ThemeOverlay.AppCompat theme is empty, we'll get the base context's theme. final ContextThemeWrapper wrappedContext = new ContextThemeWrapper(baseContext, R.style.Theme_AppCompat_Empty); wrappedContext.applyOverrideConfiguration(config); // ...... return super.attachBaseContext2(wrappedContext); }
@NonNull private static Configuration generateConfigDelta(@NonNull Configuration base, @Nullable Configuration change) { final Configuration delta = new Configuration(); delta.fontScale = 0; //...... //這里可以看到,如果兩個配置相等,則直接跳過了,并沒有給新創(chuàng)建的 delta 的 locale 賦值。 if (Build.VERSION.SDK_INT >= 24) { ConfigurationImplApi24.generateConfigDelta_locale(base, change, delta); } else { if (!ObjectsCompat.equals(base.locale, change.locale)) { delta.locale = change.locale; } } //...... }
Ok,上面注釋已經(jīng)非常清晰了。這里簡單總結(jié)下:
AppCompatActivity# attachBaseContext()
方法在 Androidx 進行了包裝,具體實現(xiàn)在 AppCompatDelegateImpl# attachBaseContext2()
。
該包裝方法實現(xiàn)了兩套邏輯:
傳入的 context 是經(jīng)過 ContextThemeWrapper 封裝的,則直接使用該 context 配置(包含語言)進行覆蓋
傳入的 context 未經(jīng)過 ContextThemeWrapper 封裝,則從 PackageManger 中獲取配置(包含語言),然后和傳入的 context 配置(包含語言)進行對比,并新創(chuàng)建了一個 configration 對象,如果兩者有對比不同的配置則賦值給這個 configration,如果相同則跳過,最后將這個新建的 configration 作為最終配置結(jié)果進行覆蓋。
而多語言問題就出現(xiàn)在 [2] 這套邏輯上,如果 PackageManager 與 傳入的 context 某個配置項一致時就不會給新建的 configration 賦值該配置項。這就會導(dǎo)致當(dāng)這一次切換成功后,殺死進程下次啟動時,由于 packageManager 配置的語言 與 context 配置的語言一致,而直接跳過,并沒有給新建的 configration進行賦值,最終表現(xiàn)就是多語言失效。
原文鏈接:https://juejin.cn/post/6915751118416904199
相關(guān)推薦
- 2022-12-12 C語言解讀數(shù)組循環(huán)右移問題_C 語言
- 2022-11-29 如果服務(wù)器出現(xiàn)內(nèi)存泄漏,堆內(nèi)存緩慢上漲,一段時間后觸發(fā)了fullGc,如何快速定位?
- 2022-02-19 RHCE安裝Apache,用瀏覽器訪問IP_Linux
- 2022-06-12 PostgreSQL聚合函數(shù)的分組排序使用示例_PostgreSQL
- 2022-05-19 C++實現(xiàn)簡單信息管理系統(tǒng)_C 語言
- 2022-07-19 Ribbon負載均衡深入探究
- 2022-03-26 C++實現(xiàn)簡單猜數(shù)字小游戲_C 語言
- 2022-11-17 C++中的函數(shù)返回值問題_C 語言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支