Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 插件化(一):改進 MultiDex 動態加載 assets 中的 apk

編輯:關於 Android 程式設計

為了繞開 65535 方法數上限,Google 提供了 MultiDex 方案來加載 classes2.dex、classes3.dex 等額外 dex,其基本思路是在運行時動態修改 ClassLoader,達到動態加載類的目的。想真正理解它,先搞清 ClassLoader 的工作機制,再看 PathClassLoader 源碼——它繼承自 BaseDexClassLoader,主要邏輯都在父類裡。

MultiDex 加載離線 apk 的流程大致如下:

合適的切入時機是 Application 的 onCreate(),或者 Activity 的 attachBaseContext()。

一、動態加載 assets 中的 apk

思路很直接:改寫 MultiDex 的 install 方法,把需要加載的 apk 從 assets 解壓到私有目錄,再調用 installSecondaryDexes 把它掛到當前 Application 的 ClassLoader 上。這樣運行時就能透過現有 ClassLoader 找到離線 apk 裡的類。

AssetsMultiDexLoader 的核心邏輯

public class AssetsMultiDexLoader {
    private static final String TAG = "AssetsApkLoader";
    private static boolean installed = false;
    private static final int MAX_SUPPORTED_SDK_VERSION = 20;
    private static final int MIN_SDK_VERSION = 4;
    private static final Set<String> installedApk = new HashSet<>();

    public static void install(Context context) {
        if (installed) return;
        try {
            clearOldDexDir(context);
        } catch (Throwable t) {
            Log.w(TAG, "清理舊 dex 目錄失敗,繼續執行", t);
        }
        // 把 assets 裡的 apk 拷貝到私有目錄
        AssetsManager.copyAllAssetsApk(context);

        try {
            ClassLoader loader = context.getClassLoader();
            if (loader == null) {
                Log.e(TAG, "ClassLoader 為空,可能處於測試環境,跳過修補");
                return;
            }
            // 取出解壓後的 apk 列表
            File dexDir = context.getDir(AssetsManager.APK_DIR, Context.MODE_PRIVATE);
            File[] szFiles = dexDir.listFiles((dir, name) -> name.endsWith(AssetsManager.FILE_FILTER));

            List<File> files = new ArrayList<>();
            for (File f : szFiles) {
                Log.i(TAG, "load file: " + f.getName());
                files.add(f);
            }
            // 關鍵:把額外 dex 掛載進 ClassLoader
            installSecondaryDexes(loader, dexDir, files);
        } catch (Exception e) {
            throw new RuntimeException("Multi dex installation failed (" + e.getMessage() + ").");
        }
        installed = true;
    }

    private static void installSecondaryDexes(ClassLoader loader, File dexDir, List<File> files)
            throws Exception {
        if (files.isEmpty()) return;
        if (Build.VERSION.SDK_INT >= 19) {
            V19.install(loader, files, dexDir);
        } else if (Build.VERSION.SDK_INT >= 14) {
            V14.install(loader, files, dexDir);
        } else {
            V4.install(loader, files);
        }
    }
}

關鍵在於反射修改 DexPathList

三個版本分支做的事本質相同:拿到 ClassLoader 的 pathList 字段,再把新的 dex 元素追加進它的 dexElements 數組。

// 通用工具方法:沿繼承鏈查找字段
private static Field findField(Object instance, String name) throws NoSuchFieldException {
    for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
        try {
            Field field = clazz.getDeclaredField(name);
            if (!field.isAccessible()) field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) { /* 繼續往上找 */ }
    }
    throw new NoSuchFieldException("Field " + name + " not found in " + instance.getClass());
}

// 數組擴展:把 extraElements 追加到實例的某個數組字段後面
private static void expandFieldArray(Object instance, String fieldName, Object[] extraElements)
        throws Exception {
    Field jlrField = findField(instance, fieldName);
    Object[] original = (Object[]) jlrField.get(instance);
    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);
}

/** Android 4.4 (API 19) 及以上 */
private static final class V19 {
    private static void install(ClassLoader loader, List<File> extra, File optimizedDirectory)
            throws Exception {
        Field pathListField = findField(loader, "pathList");
        Object dexPathList = pathListField.get(loader);
        ArrayList<IOException> suppressed = new ArrayList<>();
        expandFieldArray(dexPathList, "dexElements",
                makeDexElements(dexPathList, new ArrayList<>(extra), optimizedDirectory, suppressed));
    }

    private static Object[] makeDexElements(Object dexPathList, ArrayList<File> files,
                                            File optimizedDirectory, ArrayList<IOException> suppressed)
            throws Exception {
        Method m = findMethod(dexPathList, "makeDexElements",
                ArrayList.class, File.class, ArrayList.class);
        return (Object[]) m.invoke(dexPathList, files, optimizedDirectory, suppressed);
    }
}

/** API 4~13 的老版本差異較大,改的是 mPaths / mFiles / mZips / mDexs 四個字段 */
private static final class V4 {
    private static void install(ClassLoader loader, List<File> extra) throws Exception {
        int size = extra.size();
        Field pathField = findField(loader, "path");
        StringBuilder path = new StringBuilder((String) pathField.get(loader));

        String[]  extraPaths = new String[size];
        File[]    extraFiles = new File[size];
        ZipFile[] extraZips  = new ZipFile[size];
        DexFile[] extraDexs  = new DexFile[size];

        for (ListIterator<File> it = extra.listIterator(); it.hasNext();) {
            File entry = it.next();
            String entryPath = entry.getAbsolutePath();
            path.append(':').append(entryPath);
            int i = it.previousIndex();
            extraPaths[i] = entryPath;
            extraFiles[i] = entry;
            extraZips[i]  = new ZipFile(entry);
            extraDexs[i]  = DexFile.loadDex(entryPath, entryPath + ".dex", 0);
        }
        pathField.set(loader, path.toString());
        expandFieldArray(loader, "mPaths", extraPaths);
        expandFieldArray(loader, "mFiles", extraFiles);
        expandFieldArray(loader, "mZips",  extraZips);
        expandFieldArray(loader, "mDexs",  extraDexs);
    }
}

做版本分支的原因是各個 Android 版本的 DexPathList 內部結構變動過:API 19 起 makeDexElements 多了一個 suppressedExceptions 參數;API 14 以下甚至還沒有 DexPathList,只能去改 DexClassLoader 的四個成員。

AssetsManager:把 assets 裡的 apk 釋放到私有目錄

public class AssetsManager {
    /** apk 拷貝出來的目標目錄 */
    public static final String APK_DIR = "third_apk";
    /** 文件後綴過濾 */
    public static final String FILE_FILTER = ".apk";

    public static void copyAllAssetsApk(Context context) {
        AssetManager assetManager = context.getAssets();
        try {
            File dex = context.getDir(APK_DIR, Context.MODE_PRIVATE);
            dex.mkdir();
            String[] fileNames = assetManager.list("");
            for (String fileName : fileNames) {
                if (!fileName.endsWith(FILE_FILTER)) continue;

                InputStream in = assetManager.open(fileName);
                File f = new File(dex, fileName);
                // 已存在且大小未變則跳過,避免重複釋放
                if (f.exists() && f.length() == in.available()) {
                    in.close();
                    continue;
                }
                OutputStream out = new FileOutputStream(f);
                byte[] buffer = new byte[2048];
                int read;
                while ((read = in.read(buffer)) != -1) out.write(buffer, 0, read);
                out.flush();
                out.close();
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

這裡有個實用細節:拷貝前比對文件大小,內容未變就跳過,避免每次冷啟動都重複釋放 apk 拖慢啟動速度。

二、Demo 運行

步驟如下:

1、打開 BundleApk 項目編譯成 apk;

2、把 BundleApk.apk 拷貝到 HostApk 項目的 assets 目錄;

3、在 HostApk 的 MainActivity.onCreate 中調用:

AssetsMultiDexLoader.install(getApplicationContext());

由於宿主工程並沒有編譯期依賴 BundleApk 的類,加載後需要以反射方式調用。兩種寫法都可以:

方式一:Class.forName

private void loadClass() {
    try {
        Class<?> clazz = Class.forName("net.mobctrl.normal.apk.FileUtils");
        Object target = clazz.getConstructor().newInstance();
        Method print = clazz.getMethod("print", Context.class, String.class);
        print.setAccessible(true);
        print.invoke(target, getApplicationContext(), "Hello");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

方式二:ClassLoader.loadClass

private void loadApk() {
    try {
        Class<?> clazz = getClassLoader().loadClass("net.mobctrl.normal.apk.Utils");
        Object target = clazz.getConstructor().newInstance();
        Method printSum = clazz.getMethod("printSum",
                Context.class, int.class, int.class, String.class);
        printSum.setAccessible(true);
        Integer sum = (Integer) printSum.invoke(target, getApplicationContext(), 10, 20, "計算結果");
        System.out.println("debug: sum = " + sum);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

延伸思考

把這套機制放在 Application.onCreate 裡,就得到了最原始的「插件化」能力:宿主不需要在編譯期知道插件的任何類,插件可以獨立開發、獨立打包,運行時才被掛載進來。

當然這只是入門。真正可用的插件化框架還要解決資源加載(AssetManager 的合併)、四大組件的代理與生命週期管理、以及 ClassLoader 隔離等問題。理解 MultiDex 的反射改寫原理,是讀懂那些框架的前置知識。

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