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

Android 免安裝動態載入 APK:從 ClassLoader 到資源修復的完整實作

編輯:關於 Android 開發

免安裝動態載入 APK:把 ClassLoader 換掉就夠了

插件化、熱修復、免安裝啟動,這些名詞背後其實都繞不開同一個問題:怎樣讓一個沒有安裝的 APK(或 DEX)裡的 Activity 正常跑起來,並且擁有完整的生命週期。本文把這條路從原理到踩坑完整走一遍。

一、先補基礎:虛擬機是怎麼找到一個類的

Java 虛擬機的啟動可以拆成幾步:啟動虛擬機 → 建立 ClassLoader → 把位元組碼載入 ClassLoader → 找到入口函數執行。程式執行過程中若需要 new 一個物件,虛擬機會先在記憶體裡查找對應的 class;找不到時,才交給 ClassLoader 依路徑把 .class 檔案讀進記憶體並解析。

也就是說,ClassLoader 的本質是「按需裝載的補給站」——虛擬機從來不會一次把所有 class 都載入。Android 的 Dalvik/ART 在這方面的行為與標準 JVM 幾乎一致。

二、關鍵洞察:讓系統幫我們管理插件

我們都知道,用 DexClassLoader 載入的 Activity 是沒有生命週期的,因為系統的 ActivityManagerService 根本不認識它。但既然類查找這件事本身是由 ClassLoader 負責的,那麼——

如果我們能拿到虛擬機正在使用的那個 ClassLoader,把插件的 DEX 掛到它的查找鏈上,系統是不是就「自然而然」能找到插件的類了?

沿著這個思路,我們從應用程式進入點開始翻源碼。

三、追蹤源碼:ActivityThread 與 LoadedApk

先看 ZygoteInit.java,它是應用行程的孵化入口,透過反射呼叫 ActivityThread.main():

static void invokeStaticMain(ClassLoader loader, String className, String[] argv)
        throws ZygoteInit.MethodAndArgsCaller {
    Class<?> cl;
    try {
        cl = loader.loadClass(className);
    } catch (ClassNotFoundException ex) {
        throw new RuntimeException("Missing class when invoking static main " + className, ex);
    }
    Method m;
    try {
        // 此處反射呼叫 ActivityThread 的 main 方法
        m = cl.getMethod("main", new Class[] { String[].class });
    } catch (NoSuchMethodException ex) {
        throw new RuntimeException("Missing static main on " + className, ex);
    } catch (SecurityException ex) {
        throw new RuntimeException("Problem getting static main on " + className, ex);
    }
    int modifiers = m.getModifiers();
    if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
        throw new RuntimeException("Main method is not public and static on " + className);
    }
    // 這個 throw 會被 ZygoteInit.main() 攔下,藉此清掉所有設定行程用的堆疊框
    throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}

接著在 ActivityThread.main() 中,會建立一個 ActivityThread 實例並進入 Looper 迴圈:

public static void main(String[] args) {
    Looper.prepareMainLooper();
    ActivityThread thread = new ActivityThread();
    thread.attach(false);
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

那麼 ActivityThread 裡有什麼值得我們關注的欄位?

// mPackages 就是那把鎖;activity / window manager 會回呼叫進來更新資源配置
final ArrayMap<String, LoadedApk> mPackages = new ArrayMap<String, LoadedApk>();
final ArrayMap<String, LoadedApk> mResourcePackages = new ArrayMap<String, LoadedApk>();
final ArrayList<ActivityClientRecord> mRelaunchingActivities = new ArrayList<ActivityClientRecord>();

我們只關心 mPackages:它以包名為 key,存放 LoadedApk 物件。翻開 LoadedApk.java:

public final class LoadedApk {
    private final ActivityThread mActivityThread;
    private ApplicationInfo mApplicationInfo;
    final String mPackageName;
    private final String mAppDir;
    private final String mResDir;
    // ...
    private final ClassLoader mBaseClassLoader;
    // 注意:這個 ClassLoader 不是 final
    private ClassLoader mClassLoader;
    private Application mApplication;
    Application getApplication() { return mApplication; }
}

重點來了:mClassLoader 不是 final。實測驗證(把日誌打進這裡並自行編譯系統原始碼跑測程式)可以確認,這正是我們要換掉的那個物件。換言之,只要用反射把它替換成自訂的 ClassLoader,我們就拿到了「讓系統幫我們找類」的能力。

四、Android 的 ClassLoader 體系

Android 對外公開兩個 ClassLoader:PathClassLoader 與 DexClassLoader,兩者都繼承自 BaseDexClassLoader。建構 DexClassLoader 時的簽名如下:

public DexClassLoader(String dexPath, String optimizedDirectory,
                      String libraryPath, ClassLoader parent)

parent 參數的作用,是決定「找不到時往哪裡退」。查找規則是雙親委派:先問自己是否已載入過,再往上一層父 ClassLoader 查找,一路到最頂層都沒有,才回到自己這層去 findClass()。

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;
}

把上面兩段拼起來,結論就很清楚了:

把 LoadedApk.mClassLoader 換成我們的 DexClassLoader,並把原本那個 ClassLoader 設為新 ClassLoader 的 parent。這樣一來,原宿主 APK 的類照樣找得到(沿委派鏈往上),插件的 DEX 也能找到(自己這層 findClass)。

五、動手實作:替換 ClassLoader

public class MainActivity extends AppCompatActivity {
    private static final String ACTIVITY_THREAD_CLASS_PATH = "android.app.ActivityThread";
    private static final String GET_CURRENT_ACTIVITY_THREAD_METHOD_NAME = "currentActivityThread";
    private static final String ACTIVITY_THREAD_PACKAGES = "mPackages";
    private static final String LOAD_APK_CLASS_PATH = "android.app.LoadedApk";
    private static final String LOAD_APK_CLASS_LOADER_FILED_NAME = "mClassLoader";
    private static final String APK_NAME = "app-debug.apk";
    private static final String PLUGIN_APK_PATH =
            Environment.getExternalStorageDirectory().getPath() + File.separator + APK_NAME;
    private static String PLUGIN_APK_INTENER_PATH;
    private static String DEX_OUT_PUT_PATH;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DEX_OUT_PUT_PATH = getApplicationContext().getFilesDir().getPath();
        init();
        initLoadPlugin();
    }

    @Override
    public void onResume() {
        super.onResume();
        DynamicApplication.getApplication().resetResource();
    }

    private void init() {
        View button = findViewById(R.id.buttonPanel);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DynamicApplication.getApplication().loadPlugInResources(PLUGIN_APK_INTENER_PATH);
                Intent intent = new Intent();
                intent.setClassName(MainActivity.this, "smither.gionee.com.plugin.PluginActivity");
                ResolveInfo info = getPackageManager().resolveActivity(intent, 0);
                if (null != info) {
                    startActivity(intent);
                }
            }
        });
    }

    /** 把 ActivityThread.mPackages 中本包對應的 LoadedApk.mClassLoader 換掉 */
    private void replaceApkClassLoader(DexClassLoader classLoader) throws Exception {
        Object currentActivityThread = RefInvoke.invokeStaticMethod(
                ACTIVITY_THREAD_CLASS_PATH, GET_CURRENT_ACTIVITY_THREAD_METHOD_NAME,
                new Class[]{}, new Object[]{});
        String currentPackageName = getPackageName();
        ArrayMap activityThreadPackages = (ArrayMap) RefInvoke.getFieldOjbect(
                ACTIVITY_THREAD_CLASS_PATH, currentActivityThread, ACTIVITY_THREAD_PACKAGES);
        WeakReference loadApk = (WeakReference) activityThreadPackages.get(currentPackageName);
        RefInvoke.setFieldOjbect(LOAD_APK_CLASS_PATH, LOAD_APK_CLASS_LOADER_FILED_NAME,
                loadApk.get(), classLoader);
    }

    private void initLoadPlugin() {
        if (new File(PLUGIN_APK_PATH).exists()) {
            try {
                String copyApkPath = copyDex().getPath();
                DexClassLoader classLoader =
                        new DexClassLoader(copyApkPath, DEX_OUT_PUT_PATH, null, getClassLoader());
                replaceApkClassLoader(classLoader);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(this, "PLUGIN_APK_PATH is not exists", Toast.LENGTH_SHORT).show();
        }
    }

    private File copyDex() throws IOException {
        File file = new File(getApplicationContext().getFilesDir() + File.separator + APK_NAME);
        File plugIn1 = new File(PLUGIN_APK_PATH);
        if (!file.exists()) {
            file.createNewFile();
        }
        if (plugIn1.length() != file.length()) {
            FileOutputStream outputStream = new FileOutputStream(file);
            FileInputStream fileInputStream = new FileInputStream(plugIn1);
            byte[] buffer = new byte[fileInputStream.available()];
            fileInputStream.read(buffer);
            fileInputStream.close();
            outputStream.write(buffer);
            outputStream.close();
        }
        PLUGIN_APK_INTENER_PATH = file.getPath();
        return file;
    }
}

插件端(smither.gionee.com.plugin.PluginActivity)本身就是一個空的 Activity,沒有特別之處。至此理論上「免安裝動態載入 Activity」已經成立。

六、坑一:Activity 沒有在 Manifest 註冊

跑起來之後你會發現,startActivity() 直接拋 ActivityNotFoundException。原因是 DexClassLoader 只處理了位元組碼,不會幫你合併 AndroidManifest.xml。解法:在宿主 App 的 Manifest 中預先宣告這個 Activity(用真實的類名,不要寫假的佔位元件)。

七、坑二:資源 ID 對不上,畫面一片空白

下一個問題更棘手:頁面跳出來了,但 View 不見了,或者顯示的不是你寫的那個佈局。

原因在於資源。每個 APK 的 R 類都是編譯期各自生成的整數常數,插件裡的 R.layout.activity_plugin 可能等於 0x7f030012,而宿主裡這個 ID 指向的完全是另一張圖。當你呼叫 setContentView(R.layout.xxx),系統拿著插件的 ID 去宿主的資源表裡查,自然查不到。

但這裡有個關鍵事實:DexClassLoader 載入的 Activity 並不會產生新的 Application。Application 必須由 Zygote fork 新行程才會建立,所以插件 Activity 拿到的 getApplication() 其實是宿主的 Application 物件。

這正好是我們的突破口:既然 Application 只有一個,那就在這個 Application 上動手腳,讓它能切換資源來源。

八、自訂 Application:動態掛載插件資源

做法是透過反射呼叫 AssetManager.addAssetPath(),把插件 APK 加進 AssetManager,再用它 new 一個新的 Resources,然後重寫 getResources() / getTheme():

public class DynamicApplication extends Application {
    private Resources mResource;
    private Resources.Theme mTheme;
    private AssetManager mAssetManager;
    private static DynamicApplication mApplication;

    public static DynamicApplication getApplication() { return mApplication; }

    @Override
    public void onCreate() {
        super.onCreate();
        mApplication = this;
    }

    /** 回到宿主的資源,避免離開插件後仍拿到插件的資源 */
    public void resetResource() {
        mResource = super.getResources();
        mTheme = super.getTheme();
    }

    @Override
    public Resources getResources() {
        return mResource == null ? super.getResources() : mResource;
    }

    @Override
    public Resources.Theme getTheme() {
        return mTheme == null ? super.getTheme() : mTheme;
    }

    /** 把插件 APK 掛進 AssetManager,並據此建立新的 Resources */
    public void loadPlugInResources(String dexPath) {
        try {
            AssetManager assetManager = AssetManager.class.newInstance();
            Method addAssetPathMethod = assetManager.getClass().getMethod("addAssetPath", String.class);
            addAssetPathMethod.invoke(assetManager, dexPath);
            mAssetManager = assetManager;
            Resources superResources = super.getResources();
            mResource = new Resources(assetManager,
                    superResources.getDisplayMetrics(), superResources.getConfiguration());
            mTheme = mResource.newTheme();
            mTheme.setTo(super.getTheme());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

插件端建立 View 時,要記得把 Context 換成 getApplication(),讓 LayoutInflater 走到我們重寫過的 getResources():

// 兩種寫法等效:inflate() 內部本來就會呼叫 getContext().getResources().getLayout()
View view = LayoutInflater.from(getApplication()).inflate(R.layout.activity_plugin, null);
// View view = LayoutInflater.from(getApplication())
//         .inflate(getApplication().getResources().getLayout(R.layout.activity_plugin), null);
setContentView(view);

把實測日誌貼出來對照,可以清楚看到 Context 與 Application 是同一個物件,因此資源查表走的是 DynamicApplication 重寫後的版本:

01-15 08:47:31.027 V/PluginActivity(14208): onCreate
01-15 08:47:31.028 V/PluginActivity(14208): LayoutInflater inside Context:smither.gionee.com.dynamicmain.DynamicApplication@e6b7a3 Application:smither.gionee.com.dynamicmain.DynamicApplication@e6b7a3
01-15 08:47:31.028 V/PluginActivity(14208): LayoutInflater inside Context == getApplication() :true
01-15 08:47:31.030 V/PluginActivity(14208): getApplication getResources().getString(R.string.app_name):Plugin real app name:Plugin
01-15 08:47:31.040 V/PluginActivity(14208): Current Package Name:smither.gionee.com.dynamicmain Real package name:smither.gionee.com.plugin

注意最後兩行:getPackageName() 回傳的仍是宿主包名,但資源已經正確指向插件——這正是「行程共用、資源分離」的體現。

九、小結與注意事項

  • 核心手段只有兩個反射操作:換 ClassLoader 解決「類找得到」,換 Resources 解決「資源找得到」。
  • Activity 必須在宿主 Manifest 中預先宣告,這是繞不過去的系統限制。
  • 本文示範的是較早期的做法,全部依賴反射存取非公開欄位,在不同 Android 版本、不同 ROM 上欄位名稱與可見性都可能改變,屬於高風險的相容性方案。
  • 現代專案若要做動態化,建議改用官方支援的 Dynamic Feature / Play Feature Delivery,或使用成熟的開源插件化框架,並自行評估其維護狀態與合規風險。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved