編輯:關於 Android 程式設計
一、Android 的 ClassLoader 體系

要理解 MultiDex 與熱修復,得先從 ClassLoader 說起。我們知道 apk 本質上是包含 classes.dex 的 zip 包,而 PathClassLoader 是應用默認的類加載器。下面通過一段常見的「加載外部 apk」代碼切入:
is = getAssets().open("app.apk");
file = new File(getFilesDir(), "plugin.apk");
fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.flush();
String apkPath = file.getAbsolutePath();
dexClassLoader = new DexClassLoader(apkPath, getFilesDir().getAbsolutePath(), null, getClassLoader());
來看看 DexClassLoader 的構造函數:
public class DexClassLoader extends BaseDexClassLoader {
// dexPath:加載 apk/dex/jar 的路徑
// optimizedDirectory:dex 的輸出路徑(加載 apk/jar 時會解壓出 dex 文件並保存在此)
// libraryPath:加載時需要用到的 lib 庫,一般不用
// parent:指定父加載器
public DexClassLoader(String dexPath, String optimizedDirectory, String libraryPath, ClassLoader parent) {
super(dexPath, new File(optimizedDirectory), libraryPath, parent);
}
}
它調用了父類構造函數,於是接著看 BaseDexClassLoader:
public BaseDexClassLoader(String dexPath, File optimizedDirectory, String libraryPath, ClassLoader parent) {
super(parent);
this.pathList = new DexPathList(this, dexPath, libraryPath, optimizedDirectory);
}
可以看到它創建了一個 DexPathList 實例,再來看 DexPathList 的構造:
private final Element[] dexElements;
// definingContext 即當前 classLoader;dexPath 為傳入的 apk/dex/jar 路徑;
// libraryPath 為加載所需的 lib 庫目錄;optimizedDirectory 為 dex 輸出路徑
public DexPathList(ClassLoader definingContext, String dexPath, String libraryPath, File optimizedDirectory) {
ArrayList suppressedExceptions = new ArrayList();
this.dexElements = makeDexElements(splitDexPath(dexPath), optimizedDirectory, suppressedExceptions);
}
它調用了 makeDexElements 方法,這個方法會返回一個裝有 dex 文件的 Element[] 數組,每個 Element 對象裡都包含一個 DexFile 成員,對應的就是 dex 文件。
static class Element {
private final File file;
private final boolean isDirectory;
private final File zip;
private final DexFile dexFile;
......
}
先看看 makeDexElements 方法:
// files 為 apk/dex/jar 文件列表,可指定多個;optimizedDirectory 為 dex 輸出路徑
private static Element[] makeDexElements(ArrayList files, File optimizedDirectory, ArrayList suppressedExceptions) {
ArrayList elements = new ArrayList();
for (File file : files) {
File zip = null;
DexFile dex = null;
String name = file.getName();
// 如果是 dex 文件
if (name.endsWith(DEX_SUFFIX)) {
try {
dex = loadDexFile(file, optimizedDirectory);
} catch (IOException ex) {
System.logE("Unable to load dex file: " + file, ex);
}
// 如果是 apk/jar/zip 文件
} else if (name.endsWith(APK_SUFFIX) || name.endsWith(JAR_SUFFIX) || name.endsWith(ZIP_SUFFIX)) {
zip = file;
try {
dex = loadDexFile(file, optimizedDirectory);
} catch (IOException suppressed) {
suppressedExceptions.add(suppressed);
}
} else if (file.isDirectory()) {
elements.add(new Element(file, true, null, null));
} else {
System.logW("Unknown file type for: " + file);
}
if ((zip != null) || (dex != null)) {
elements.add(new Element(file, false, zip, dex));
}
}
return elements.toArray(new Element[elements.size()]);
}
現在再看 Element 具體包含哪些成員就一目了然了:
static class Element {
private final File file; // 需要加載的 apk/dex/jar 文件
private final boolean isDirectory; // file 是否為目錄,一般為 false
private final File zip; // 若加載的是 apk/jar/zip,該對象即為該文件
private final DexFile dexFile; // 得到的 dex 文件
......
}
可以看到它調用了 loadDexFile 方法:
// file 為需加載的 apk/dex/jar;optimizedDirectory 為 dex 輸出路徑
private static DexFile loadDexFile(File file, File optimizedDirectory) throws IOException {
if (optimizedDirectory == null) {
return new DexFile(file);
} else {
String optimizedPath = optimizedPathFor(file, optimizedDirectory);
return DexFile.loadDex(file.getPath(), optimizedPath, 0);
}
}
若未指定 dex 輸出目錄,就直接創建 DexFile 對象;若指定了,則需構造輸出 dex 路徑。optimizedPathFor 方法用來得到輸出文件路徑,即 optimizedDirectory/filename.dex。重點來看 DexFile.loadDex:
static public DexFile loadDex(String sourcePathName, String outputPathName, int flags) throws IOException {
return new DexFile(sourcePathName, outputPathName, flags);
}
到此可以總結一下:① 在 DexClassLoader 中指定加載的文件和 dex 輸出路徑,最終解析得到 DexFile;② 把 DexFile 放進 Element 的 dexFile 成員;③ 把 Element 放進 Element[] 數組,返回給 DexPathList 的 dexElements;④ DexPathList 又是 BaseDexClassLoader 的成員變量。最終,我們得到一個裝有 dex 文件的數組 Element[]。

二、加載指定 Class
通過 dexClassLoader.loadClass 得到加載的 dex 裡的指定類:
clazz = dexClassLoader.loadClass("com.example.apkplugin.PluginTest");
由於 DexClassLoader 和 BaseDexClassLoader 都沒有實現 loadClass,最終調用的是 ClassLoader 的 loadClass:
protected Class loadClass(String className, boolean resolve) throws ClassNotFoundException {
Class clazz = findLoadedClass(className);
if (clazz == null) {
ClassNotFoundException suppressed = null;
try {
clazz = parent.loadClass(className, false);
} catch (ClassNotFoundException e) {
suppressed = e;
}
if (clazz == null) {
try {
clazz = findClass(className);
} catch (ClassNotFoundException e) {
e.addSuppressed(suppressed);
throw e;
}
}
}
return clazz;
}
它調用了 findClass,而這個方法由 BaseDexClassLoader 實現:
@Override
protected Class findClass(String name) throws ClassNotFoundException {
List suppressedExceptions = new ArrayList();
Class c = pathList.findClass(name, suppressedExceptions);
if (c == null) {
throw new ClassNotFoundException("Didn't find class \"" + name + "\" on path: " + pathList);
}
return c;
}
pathList 就是前面創建的 DexPathList,dex 文件都存在它的 dexElements 數組裡,因此 BaseDexClassLoader 的 findClass 又轉調了 DexPathList 的 findClass:
public Class findClass(String name, List suppressed) {
for (Element element : dexElements) {
DexFile dex = element.dexFile;
if (dex != null) {
Class clazz = dex.loadClassBinaryName(name, definingContext, suppressed);
if (clazz != null) {
return clazz;
}
}
}
return null;
}
它就是遍歷 dexElements 數組,從每個 Element 中取出 DexFile,再從中查找所需 class,找到即返回,找不到則繼續下一個。
總結:一個 ClassLoader 可以包含多個 dex 文件,每個 dex 對應一個 Element,多個 Element 排列成有序數組 dexElements。查找類時會按順序遍歷,找到即返回,否則繼續下一個。
三、MultiDex 基本原理
當一個 app 功能越來越複雜、代碼量越來越大,就會遭遇兩個典型問題:① 生成的 apk 在 2.3 以前的機器上無法安裝,提示 INSTALL_FAILED_DEXOPT;② 方法數量過多導致編譯報錯:Conversion to Dalvik format failed: Unable to execute dex: method ID not in [0, 0xffff]: 65536。
原因在於:① Android 2.3 及更早版本用於執行 dexopt 的內存僅分配了 5M;② 單個 dex 文件最多只支持 65536 個方法。
解決方案有兩種:① 使用 MultiDex,把編譯好的 class 拆分打包成多個 dex,繞過方法數上限與安裝檢查,運行時再動態加載;② 使用插件化,將功能模塊分離,減少宿主 apk 的體積與代碼量。
這裡重點說 MultiDex 的基本原理:① 除第一個 dex(正常 apk 唯一包含的 dex)外,其餘 dex 都以資源形式放在安裝包中,需要在 Application 的 onCreate 回調裡注入到系統的 ClassLoader;對於在注入前已被引用的類(及其所在 jar),必須放入第一個 dex。② PathClassLoader 作為默認類加載器,打開應用時會自動加載第一個 dex,因此我們要做的就是把它剩下的 dex 也注入進去。③ 由於 PathClassLoader 內部的 dex 也是放在 Element 數組裡,只要把其他 dex 也放進這個數組即可。
實現步驟:① 通過反射獲取 PathClassLoader 中 DexPathList 的 Element 數組(已含系統加載的第一個 dex);② 通過反射獲取 DexClassLoader 中 DexPathList 的 Element 數組(含第二個 dex);③ 將兩個數組合並後,再賦值回 PathClassLoader 的 Element 數組。
谷歌提供的 MultiDex 支持庫正是按此思路實現的。使用上很簡單,先修改 Gradle 配置開啟 multidex:
android {
compileSdkVersion 21
buildToolsVersion "21.1.0"
defaultConfig {
minSdkVersion 14
targetSdkVersion 21
multiDexEnabled true
}
}
dependencies {
compile 'com.android.support:multidex:1.0.0'
}
再在 manifest 的 application 標籤下引用 MultiDexApplication。來看看它的源碼:
public class MultiDexApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
可見要求使用 MultiDexApplication,正是為了重寫 attachBaseContext,把其他 dex 注入到系統 ClassLoader。進入 install 方法:
public static void install(Context context) {
// SDK 版本判斷略
ApplicationInfo e = getApplicationInfo(context);
synchronized (installedApk) {
String apkPath = e.sourceDir; // 得到本應用的 apk 路徑
if (installedApk.contains(apkPath)) {
return;
}
installedApk.add(apkPath);
ClassLoader loader = context.getClassLoader(); // 即 PathClassLoader
File dexDir = new File(e.dataDir, SECONDARY_FOLDER_NAME);
// 從 apk 中提取其他 dex 文件到 data 目錄
List files = MultiDexExtractor.load(context, e, dexDir, false);
if (checkValidZipFiles(files)) {
installSecondaryDexes(loader, dexDir, files);
} else {
files = MultiDexExtractor.load(context, e, dexDir, true);
installSecondaryDexes(loader, dexDir, files);
}
}
}
重點看 installSecondaryDexes:
private static void installSecondaryDexes(ClassLoader loader, File dexDir, List files) throws ... {
if (!files.isEmpty()) {
if (VERSION.SDK_INT >= 19) {
MultiDex.V19.install(loader, files, dexDir);
} else if (VERSION.SDK_INT >= 14) {
MultiDex.V14.install(loader, files, dexDir);
} else {
MultiDex.V4.install(loader, files);
}
}
}
可以看到不同 SDK 版本實現有差別(因為用了反射)。以 V14 為例:
private static void install(ClassLoader loader, List additionalClassPathEntries, File optimizedDirectory) throws ... {
// 反射得到 loader 的 pathList 字段
Field pathListField = MultiDex.findField(loader, "pathList");
Object dexPathList = pathListField.get(loader);
// 將其他 dex 的 Element 數組與第一個 dex 的 Element 數組合並
MultiDex.expandFieldArray(dexPathList, "dexElements",
makeDexElements(dexPathList, new ArrayList(additionalClassPathEntries), optimizedDirectory));
}
合並過程如下:
private static void expandFieldArray(Object instance, String fieldName, Object[] extraElements) throws ... {
Field jlrField = findField(instance, fieldName);
Object[] original = (Object[]) jlrField.get(instance); // 原有的 dexElements
Object[] combined = (Object[]) Array.newInstance(
original.getClass().getComponentType(), original.length + extraElements.length);
System.arraycopy(original, 0, combined, 0, original.length); // 複製原數組
System.arraycopy(extraElements, 0, combined, original.length, extraElements.length); // 追加新數組
jlrField.set(instance, combined); // 賦值回去
}
整體思路與前面介紹的完全一致,理解思路後結合註釋就很清晰了。
四、熱修復的一種實現原理
回顧前面的結論:一個 ClassLoader 包含多個 dex,每個 dex 是一個 Element,組成有序數組 dexElements;查找類時按順序遍歷,找到即返回。那麼理論上,如果不同的 dex 中存在同名的類,系統會優先選擇排在前面的那個。

於是可以這麼做:把需要修復的、有問題的類打包到一個獨立的 dex(patch.dex)中,再將這個 dex 插入到 dexElements 數組的最前面。

這樣,當系統加載同名類時,就會命中位於最前端的修復版本,從而達到「熱修復」的效果——無需重新發版即可修復線上問題。
XListView 詳解:下拉重新整理與上拉載入的實現原理
XListView 是一個常見的開源列表控制項,主要提供下拉重新整理與上拉載入更多功能。它在原生 ListView 的基礎上加入了頭部與底部視圖,並透過觸控事件與捲動回調
Android 記憶體分析工具全面總結
Android 的一些記憶體知識 垃圾回收(GC) 垃圾回收包含兩個過程:判定階段(判斷哪些物件可以被回收)與收集階段(具體的回收策略)。 判定階段主要有兩種方式: 引用
Android 高頻 UI 元件一把抓:自訂對話框、進度提示、下拉重新整理與 Popup 彈出層
做專案的時候,對話框、載入進度、下拉重新整理、彈出式選單這幾樣東西幾乎每個 App 都躲不掉。麻煩的是每次都要重新翻開源專案找一次、改一次,時間就這樣被吃掉了。 這份 d
RecyclerView 進階:Item 拖拽排序與滑動刪除的完整封裝
效果先看 需求拆解與技術選型 要實現兩個交互: 拖拽排序——長按 RecyclerView 的 Item,或者觸摸 Item 上的某個指定按鈕,進入拖拽狀態,放手後完