Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Android 切換系統語言源碼分析

編輯:Android 資訊

以前以為 Android 的多語言實現很簡單:在不同語言環境下使用不同資源,做好適配即可。但一直沒有實踐過。最近公司項目需要多國語言切換,而且還要和系統設置裡的語言切換功能一模一樣,於是上網查了資料。

在應用類裡實現多語言切換很簡單,但我想切換的是整個系統的語言。由於 Google 並未開放系統設置的相關接口,只好去啃源碼。

Android 的語言切換在以下文件的 updateLocale() 函數中調用:

packages/apps/Settings/com/android/settings/LocalePicker.java

源碼如下:

/** * Requests the system to update the system locale. Note that the system looks halted for a while during the Locale migration, so the caller need to take care of it. */ public static void updateLocale(Locale locale) { try { IActivityManager am = ActivityManagerNative.getDefault(); Configuration config = am.getConfiguration(); config.locale = locale; // indicate this isn't some passing default - the user wants this remembered config.userSetLocale = true; am.updateConfiguration(config); // Trigger the dirty bit for the Settings Provider. BackupManager.dataChanged("com.android.providers.settings"); } catch (RemoteException e) { // Intentionally left blank } }

從註釋可見,只要本地 locale 改變就會調用該函數。查看 ActivityManagerNative 的 getDefault() 可知,它返回的是遠程服務 ActivityManagerService.java 在本地的代理,最終調用的是 ActivityManagerService.java 中的 updateConfiguration():

public void updateConfiguration(Configuration values) { enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION, "updateConfiguration()"); synchronized(this) { if (values == null && mWindowManager != null) { values = mWindowManager.computeNewConfiguration(); } if (mWindowManager != null) { mProcessList.applyDisplaySize(mWindowManager); } final long origId = Binder.clearCallingIdentity(); if (values != null) { Settings.System.clearConfiguration(values); } updateConfigurationLocked(values, null, false, false); Binder.restoreCallingIdentity(origId); } }

該函數先做權限校驗,再調用 updateConfigurationLocked():

public boolean updateConfigurationLocked(Configuration values, ActivityRecord starting, boolean persistent, boolean initLocale) { int changes = 0; boolean kept = true; if (values != null) { Configuration newConfig = new Configuration(mConfiguration); changes = newConfig.updateFrom(values); if (changes != 0) { // ... 省略日誌與配置更新邏輯 ... if (values.locale != null && !initLocale) { saveLocaleLocked(values.locale, !values.locale.equals(mConfiguration.locale), values.userSetLocale, values.simSetLocale); } mConfigurationSeq++; newConfig.seq = mConfigurationSeq; mConfiguration = newConfig; final Configuration configCopy = new Configuration(mConfiguration); // 更新本進程所有資源 mSystemThread.applyConfigurationToResources(configCopy); // 遍歷所有進程,下發新配置 for (int i=mLruProcesses.size()-1; i>=0; i--) { ProcessRecord app = mLruProcesses.get(i); try { if (app.thread != null) { app.thread.scheduleConfigurationChanged(configCopy); } } catch (Exception e) { } } // 廣播配置變更 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED); // ... if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) { broadcastIntentLocked(new Intent(Intent.ACTION_LOCALE_CHANGED), ...); } } } // ... 確保頂層 Activity 配置正確 return kept; }

整個語言切換就在這個函數中完成。看註釋可知它做了兩件事:(1) 改變當前 configuration;(2) 確保所有正在運行的 Activity 都能更新到改變後的 configuration(這一點是關鍵)。

先看 changes = newConfig.updateFrom(values),查看 updateFrom 的實現:

public int updateFrom(Configuration delta) { int changed = 0; if (delta.locale != null && (locale == null || !locale.equals(delta.locale))) { changed |= ActivityInfo.CONFIG_LOCALE; locale = delta.locale != null ? (Locale) delta.locale.clone() : null; textLayoutDirection = LocaleUtil.getLayoutDirectionFromLocale(locale); } if (delta.userSetLocale && (!userSetLocale || ((changed & ActivityInfo.CONFIG_LOCALE) != 0))) { userSetLocale = true; changed |= ActivityInfo.CONFIG_LOCALE; } return changed; }

因為語言變了,(!locale.equals(delta.locale)) 為 true,changed 大於 0 並返回。回到 updateConfigurationLocked,由於 changes 不為 0,便進入 if 分支,遍歷所有進程下發新配置:

for (int i=mLruProcesses.size()-1; i>=0; i--) { ProcessRecord app = mLruProcesses.get(i); try { if (app.thread != null) { app.thread.scheduleConfigurationChanged(configCopy); } } catch (Exception e) { } }

這裡 mLruProcesses 是保存所有運行過進程的 ArrayList(LRU:Least Recently Used)。ProcessRecord 是進程類,一個 apk 運行時對應一個進程。app.thread 是 ApplicationThreadNative 類型,調用其 scheduleConfigurationChanged():

public final void scheduleConfigurationChanged(Configuration config) throws RemoteException { Parcel data = Parcel.obtain(); data.writeInterfaceToken(IApplicationThread.descriptor); config.writeToParcel(data, 0); mRemote.transact(SCHEDULE_CONFIGURATION_CHANGED_TRANSACTION, data, null, IBinder.FLAG_ONEWAY); data.recycle(); }

又是一次 Binder 調用——可見 Binder 在 Android 中舉足輕重。此處遠程調用的是 ActivityThread.java 中的私有內部類 ApplicationThread:

private class ApplicationThread extends ApplicationThreadNative { public void scheduleConfigurationChanged(Configuration config) { updatePendingConfiguration(config); queueOrSendMessage(H.CONFIGURATION_CHANGED, config); } }

ApplicationThread 的 handler 在收到 CONFIGURATION_CHANGED 後調用 handleConfigurationChanged():

final void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) { ArrayList<ComponentCallbacks2> callbacks = null; applyConfigurationToResourcesLocked(config, compat); callbacks = collectComponentCallbacksLocked(false, config); if (callbacks != null) { final int N = callbacks.size(); for (int i=0; i<N; i++) { performConfigurationChanged(callbacks.get(i), config); } } }

該函數先調用 applyConfigurationToResourcesLocked(),顧名思義就是將 configuration 應用到 resources。既然改的是 locale,那 resources 裡是否含語言包呢?

final boolean applyConfigurationToResourcesLocked(Configuration config, CompatibilityInfo compat) { int changes = mResConfiguration.updateFrom(config); DisplayMetrics dm = getDisplayMetricsLocked(null, true); // ... Resources.updateSystemConfiguration(config, dm, compat); // 循環更新所有活躍資源 Iterator<WeakReference<Resources>> it = mActiveResources.values().iterator(); while (it.hasNext()) { WeakReference<Resources> v = it.next(); Resources r = v.get(); if (r != null) { r.updateConfiguration(config, dm, compat); } else { it.remove(); } } return changes != 0; }

Resources.updateSystemConfiguration() 會清除部分系統資源並把 config 更新到 Resources,而 Resources 內部包含一個 AssetManager 對象,其核心實現位於 AssetManager.cpp。回到 handleConfigurationChanged(),更新完資源後會遍歷該進程的所有 Activity:

if (callbacks != null) { final int N = callbacks.size(); for (int i=0; i<N; i++) { performConfigurationChanged(callbacks.get(i), config); } }

再看 performConfigurationChanged 的實現:

private final void performConfigurationChanged(ComponentCallbacks2 cb, Configuration config) { Activity activity = (cb instanceof Activity) ? (Activity) cb : null; boolean shouldChangeConfig = false; if ((activity == null) || (activity.mCurrentConfig == null)) { shouldChangeConfig = true; } else { int diff = activity.mCurrentConfig.diff(config); if (diff != 0) { if ((~activity.mActivityInfo.getRealConfigChanged() & diff) == 0) { shouldChangeConfig = true; } } } if (shouldChangeConfig) { cb.onConfigurationChanged(config); // ... } }

該函數判斷 configuration 是否改變,若改變則 shouldChangeConfig 為 true,接著調用 Activity 的 onConfigurationChanged(config):

/** * Called by the system when the device configuration changes while your * activity is running. Note that this will only be called if you have * selected configurations you would like to handle with the configChanges * attribute in your manifest. * * At the time that this function has been called, your Resources object * will have been updated to return resource values matching the new * configuration. */ public void onConfigurationChanged(Configuration newConfig) { mCalled = true; mFragments.dispatchConfigurationChanged(newConfig); if (mWindow != null) { mWindow.onConfigurationChanged(newConfig); } if (mActionBar != null) { mActionBar.onConfigurationChanged(newConfig); } }

看註釋可知:當設備配置(configuration)改變時,系統會調用此方法。若你在 manifest.xml 中配置了 configChanges 屬性,表示由你自己處理配置變更,否則系統會重啟當前 Activity。而重啟之前舊的 resources 已被清空,於是會裝載新資源,整個語言切換的過程就此完成,讓所有 App 都能使用新語言。

以上便是我對 Android 系統語言切換所做的源碼分析。有些細節我也未必完全看懂,能力有限,就先分析到這裡。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved