與Android熱更新方案Amigo的親密接觸

以前寫過一片:與Android熱更新方案Amigo的初次接觸,主要是記敘了Amigo的接入和使用。java

最近讀了一下Amigo的源碼,並且看了看網上其餘講Amigo源碼的文章,它們所針對的代碼都和最新的Amigo代碼有所出路,因此針對最新的代碼,淺淺的分析一下。android

Amigo的最近更新已是8個月以前了。我最近更新了Android Studio3.0,gradle版本3.1.1。可是Amigo使用的gradle版本2.3.1。若是項目仍是要使用gradle3.x版本的話,會報錯。因此我更新了Amigo插件使用的gradle版本(由於的gradle3.0比起2.0有一些修改,因此也修改了部分Amigo插件代碼),若是有使用Amigo的老鐵同時用的是gradle3.x版本的話,能夠找我要代碼。git

Amigo主要有兩個部分,在Github上能夠看到,amigo-lib和buildSrc。github

amigo-lib對應:bash

dependencies {
    ...
    compile 'me.ele:amigo-lib:0.6.7'
}
複製代碼

buildSrc對應插件:app

dependencies {
        ......
        classpath 'me.ele:amigo:0.6.8'
}
複製代碼
apply plugin: 'me.ele.amigo'
複製代碼

先說插件,這個插件的做用就是修改AndroidManifest.xml,將項目本來的Application替換稱Amigo.java,而且將原來的 application 的 name 保存在了一個名爲acd的類中。AndroidManifest.xml 中將原來的 application 作爲一個 Activity。ide

再說amigo-lib,這個是熱更新的重點。咱們從更新的入口開始提及:post

button.setOnClickListener {
            var file = File(Environment.getExternalStorageDirectory().path + File.separator + "test.apk")
            if(file.exists()){
                Amigo.workLater(this, file) {
                    if(it){
                        toast("更新成功!")
                        val intent = packageManager.getLaunchIntentForPackage(packageName)
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        startActivity(intent)
                        android.os.Process.killProcess(android.os.Process.myPid())
                    }
                }
            }
        }
複製代碼

本地已經有了一個新的APK,直接調用Amigo.workLater()開始更新。gradle

private static void workLater(Context context, File patchFile, boolean checkSignature, WorkLaterCallback callback) {
        String patchChecksum = PatchChecker.checkPatchAndCopy(context, patchFile, checkSignature);
        if (checkWithWorkingPatch(context, patchChecksum)) return;
        if (patchChecksum == null) {
            Log.e(TAG, "#workLater: empty checksum");
            return;
        }

        if (callback != null) {
            AmigoService.startReleaseDex(context, patchChecksum, callback);
        } else {
            AmigoService.startReleaseDex(context, patchChecksum);
        }
    }
複製代碼

第一步

將新的安裝包拷貝到了/data/data/{package_name}/files/amigo/{checksum}/patch.apk。checksum是根據APK算出的,每一個APK都不一樣,能夠理解爲APK的id。固然,在拷貝以前作了一些校驗,主要是之前拷貝過嗎?是否是如今正在運行的版本?

第二步

釋放Dex。在 AmigoService.startReleaseDex()中主要是啓動了AmigoService。在AmigoService.java中會調用:優化

private synchronized void handleReleaseDex(Intent intent) {
        String checksum = intent.getStringExtra(EXTRA_APK_CHECKSUM);
        if (apkReleaser == null) {
            apkReleaser = new ApkReleaser(getApplicationContext());
        }
        apkReleaser.release(checksum, msgHandler);
    }
複製代碼

具體的釋放Dex在ApkReleaser的release()中:

public void release(final String checksum, final Handler msgHandler) {
        if (isReleasing) {
            Log.w(TAG, "release : been busy now, skip release " + checksum);
            return;
        }

        Log.d(TAG, "release: start release " + checksum);
        try {
            this.amigoDirs = AmigoDirs.getInstance(context);
            this.patchApks = PatchApks.getInstance(context);
        } catch (Exception e) {
            Log.e(TAG,
                    "release: unable to create amigo dir and patch apk dir, abort release dex files",
                    e);
            handleDexOptFailure(checksum, msgHandler);
            return;
        }
        isReleasing = true;
        service.submit(new Runnable() {
            @Override
            public void run() {
                if (!new DexExtractor(context, checksum).extractDexFiles()) {
                    Log.e(TAG, "releasing dex failed");
                    handleDexOptFailure(checksum, msgHandler);
                    isReleasing = false;
                    FileUtils.removeFile(amigoDirs.dexDir(checksum), false);
                    return;
                }

                // todo
                // just create a link point to /data/app/{package_name}/libs
                // if none of the native libs are changed
                int errorCode;
                if ((errorCode =
                        NativeLibraryHelperCompat.copyNativeBinaries(patchApks.patchFile(checksum),
                                amigoDirs.libDir(checksum))) < 0) {
                    Log.e(TAG, "coping native binaries failed, errorCode = " + errorCode);
                    handleDexOptFailure(checksum, msgHandler);
                    FileUtils.removeFile(amigoDirs.dexDir(checksum), false);
                    FileUtils.removeFile(amigoDirs.libDir(checksum), false);
                    isReleasing = false;
                    return;
                }

                final boolean dexOptimized = Build.VERSION.SDK_INT >= 21 ? dexOptimizationOnArt(checksum)
                        : dexOptimizationOnDalvik(checksum);
                if (dexOptimized) {
                    Log.e(TAG, "optimize dex succeed");
                    handleDexOptSuccess(checksum, msgHandler);
                    isReleasing = false;
                    return;
                }

                Log.e(TAG, "optimize dex failed");
                FileUtils.removeFile(amigoDirs.dexDir(checksum), false);
                FileUtils.removeFile(amigoDirs.libDir(checksum), false);
                FileUtils.removeFile(amigoDirs.dexOptDir(checksum), false);
                handleDexOptFailure(checksum, msgHandler);
                isReleasing = false;
            }
        });
    }
複製代碼

這裏又分了3小步:1.釋放dex;2.釋放lib中的so;3.優化dex。

DexExtractor(context, checksum).extractDexFiles()中是具體的釋放dex過程:

public boolean extractDexFiles() {
        if (Build.VERSION.SDK_INT >= 21) {
            return true; // art supports multi-dex natively
        }

        return performExtractions(PatchApks.getInstance(context).patchFile(checksum),
                AmigoDirs.getInstance(context).dexDir(checksum));
    }

    //把patchApk(新包)中的dex解壓到dexDir:/data/data/{package_name}/files/amigo/{checksum}/dexes
private boolean performExtractions(File patchApk, File dexDir) {
        ZipFile apk = null;
        try {
            apk = new ZipFile(patchApk);
            int dexNum = 0;
            ZipEntry dexFile = apk.getEntry("classes.dex");
            for (; dexFile != null; dexFile = apk.getEntry("classes" + dexNum + ".dex")) {
                String fileName = dexFile.getName().replace("dex", "zip");
                File extractedFile = new File(dexDir, fileName);
                extract(apk, dexFile, extractedFile);
                verifyZipFile(extractedFile);
                if (dexNum == 0) ++dexNum;
                ++dexNum;
            }
            return dexNum > 0;
        } catch (IOException ioe) {
            ioe.printStackTrace();
            return false;
        } finally {
            try {
                apk.close();
            } catch (IOException var16) {
                Log.w("DexExtractor", "Failed to close resource", var16);
            }
        }
    }
複製代碼

這裏有個extract()方法,進去看一下:

private void extract(ZipFile patchApk, ZipEntry dexFile, File extractTo) throws IOException {
        boolean reused = reusePreExistedODex(patchApk, dexFile);
        Log.d(TAG, "extracted: "
                + dexFile.getName() + " success ? "
                + reused
                + ", by reusing pre-existed secondary dex");
        //能夠若是複用舊dex
        if (reused) {
            return;
        }
        //不能複用,就執行拷貝
        InputStream in = null;
        File tmp = null;
        ZipOutputStream out = null;
        try {
            in = patchApk.getInputStream(dexFile);
            tmp = File.createTempFile(extractTo.getName(), ".tmp", extractTo.getParentFile());
            try {
                out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(tmp)));
                ZipEntry classesDex = new ZipEntry("classes.dex");
                classesDex.setTime(dexFile.getTime());
                out.putNextEntry(classesDex);
                if (buffer == null) {
                    buffer = new byte[16384];
                }
                for (int length = in.read(buffer); length != -1; length = in.read(buffer)) {
                    out.write(buffer, 0, length);
                }
            } finally {
                if (out != null) {
                    out.closeEntry();
                    out.close();
                }
            }

            if (!tmp.renameTo(extractTo)) {
                throw new IOException("Failed to rename \""
                        + tmp.getAbsolutePath()
                        + "\" to \""
                        + extractTo.getAbsolutePath()
                        + "\"");
            }
        } finally {
            closeSilently(in);
            if (tmp != null) tmp.delete();
        }
    }
複製代碼

在這裏咱們看到了具體的拷貝過程,先是拷貝到了tmp文件,而後改的名。可是在拷貝以前有一個操做reusePreExistedODex(),在這個方法中判斷了當前運行的App的dex與更新包的dex是否一致,若是一致作了一個link,把當前APP的dex文件link到了咱們須要拷貝的目錄dexDir:/data/data/{package_name}/files/amigo/{checksum}/dexes,若是不一致再作拷貝操做。

到此dex釋放完畢,下一步釋放so文件。NativeLibraryHelperCompat.copyNativeBinaries()這裏就是判斷,根據不一樣的系統版本(好比是64位還32位系統),調用了不一樣拷貝方法。具體的這篇文章有詳細說。

而後就是優化dex了。final boolean dexOptimized = Build.VERSION.SDK_INT >= 21 ? dexOptimizationOnArt(checksum) : dexOptimizationOnDalvik(checksum)這裏針對系統版本調用了不一樣的方法。

第三步

保存標誌,而後重啓:

private void handleDexOptSuccess(String checksum, Handler msgHandler) {
        saveDexAndSoChecksum(checksum);
        PatchInfoUtil.updateDexFileOptStatus(context, checksum, true);
        PatchInfoUtil.setWorkingChecksum(context, checksum);
        if (msgHandler != null) {
            msgHandler.sendEmptyMessage(AmigoService.MSG_ID_DEX_OPT_SUCCESS);
        }
    }
複製代碼

到此釋放階段結束。

下面是重啓後,讀取資源。代碼在Amigo.java中,先看看attachApplication(). 在attachApplication()中先作了一系列判斷,主要是判斷是否須要讀取釋放後的文件(好比是否有更新文件,是否須要更新),咱們直接進入讀取文件的地方attachPatchApk(workingChecksum);

private void attachPatchApk(String checksum) throws LoadPatchApkException {
        try {
            if (isPatchApkFirstRun(checksum)
                    || !AmigoDirs.getInstance(this).isOptedDexExists(checksum)) {
                PatchInfoUtil.updateDexFileOptStatus(this, checksum, false);
                releasePatchApk(checksum);
            } else {
                PatchChecker.checkDexAndSo(this, checksum);
            }

            setAPKClassLoader(AmigoClassLoader.newInstance(this, checksum));
            setApkResource(checksum);
            revertBitFlag |= getClassLoader() instanceof AmigoClassLoader ? 1 : 0;
            attachPatchedApplication(checksum);
            PatchCleaner.clearOldPatches(this, checksum);
            shouldHookAmAndPm = true;
            Log.i(TAG, "#attachPatchApk: success");
        } catch (Exception e) {
            throw new LoadPatchApkException(e);
        }
    }
複製代碼

這裏有兩個地方setAPKClassLoader(AmigoClassLoader.newInstance(this, checksum)); setApkResource(checksum); 分別是設置 ClassLoader 和加載資源。

先說ClassLoader,這裏Hook了一個ClassLoader,使用了本身的AmigoClassLoader。

public static AmigoClassLoader newInstance(Context context, String checksum) {
        return new AmigoClassLoader(PatchApks.getInstance(context).patchPath(checksum),
                getDexPath(context, checksum),
                AmigoDirs.getInstance(context).dexOptDir(checksum).getAbsolutePath(),
                getLibraryPath(context, checksum),
                AmigoClassLoader.class.getClassLoader().getParent());
    }
複製代碼

經過上面的代碼能夠看出AmigoClassLoader使用了咱們以前釋放的資源的目錄,也就是dex,libs等。

private void setApkResource(String checksum) throws Exception {
        PatchResourceLoader.loadPatchResources(this, checksum);
        Log.i(TAG, "hook Resources success");
    }
static void loadPatchResources(Context context, String checksum) throws Exception {
        AssetManager newAssetManager = AssetManager.class.newInstance();
        invokeMethod(newAssetManager, "addAssetPath", PatchApks.getInstance(context).patchPath(checksum));
        invokeMethod(newAssetManager, "ensureStringBlocks");
        replaceAssetManager(context, newAssetManager);
    }
複製代碼

replaceAssetManager(context, newAssetManager)中Hook了一些其餘AssetManager用到的地方。

而後把shouldHookAmAndPm設成了true。 到這裏attachApplication()執行完成。而後走onCreate()

public void onCreate() {
        super.onCreate();
        try {
            setAPKApplication(realApplication);
        } catch (Exception e) {
            // should not happen, if it does happen, we just let it die
            throw new RuntimeException(e);
        }
        if(shouldHookAmAndPm) {
            try {
                installAndHook();
            } catch (Exception e) {
                try {
                    clear(this);
                    attachOriginalApplication();
                } catch (Exception e1) {
                    throw new RuntimeException(e1);
                }
            }
        }
        realApplication.onCreate();
    }
複製代碼

這裏有個:

private void installAndHook() throws Exception {
        boolean gotNewActivity = ActivityFinder.newActivityExistsInPatch(this);
        if (gotNewActivity) {
            setApkInstrumentation();
            revertBitFlag |= 1 << 1;
            setApkHandlerCallback();
            revertBitFlag |= 1 << 2;
        } else {
            Log.d(TAG, "installAndHook: there is no any new activity, skip hooking " +
                    "instrumentation & mH's callback");
        }
        installHookFactory();
        dynamicRegisterNewReceivers();
        installPatchContentProviders();
    }
複製代碼

首先判斷是否有新的Activity,若是有,就須要HookmInstrumentationinstallHookFactory()中替換了ClassLoader,動態註冊了Receiver,安裝ContentProvider。

最後調用attachOriginalApplication(),把以前的Application替換回來,而後走正常的流程。


【2018/10/11】

最近,適配了Android O。有須要的,拿去-> github

相關文章
相關標籤/搜索