Android 熱修復 Tinker接入及源碼淺析

本文已在個人公衆號hongyangAndroid首發。
轉載請標明出處:
gold.xitu.io/post/589736…
本文出自張鴻洋的博客javascript

1、概述

放了一個大長假,happy,先祝你們2017年笑口常開。java

熱修復這項技術,基本上已經成爲項目比較重要的模塊了。主要由於項目在上線以後,都不免會有各類問題,而依靠發版去修復問題,成本過高了。android

如今熱修復的技術基本上有阿里的AndFix、QZone的方案、美團提出的思想方案以及騰訊的Tinker等。git

其中AndFix可能接入是最簡單的一個(和Tinker命令行接入方式差很少),不過兼容性仍是是有必定的問題的;QZone方案對性能會有必定的影響,且在Art模式下出現內存錯亂的問題(其實這個問題我以前並不清楚,主要是tinker在MDCC上指出的);美團提出的思想方案主要是基於Instant Run的原理,目前還沒有開源,不過這個方案我仍是蠻喜歡的,主要是兼容性好。github

這麼看來,若是選擇開源方案,tinker目前是最佳的選擇,tinker的介紹有這麼一句:算法

Tinker已運行在微信的數億Android設備上,那麼爲何你不使用Tinker呢?api

好了,說了這麼多,下面來看看tinker如何接入,以及tinker的大體的原理分析。但願經過本文能夠實現幫助你們更好的接入tinker,以及去了解tinker的一個大體的原理。數組

2、接入Tinker

接入tinker目前給了兩種方式,一種是基於命令行的方式,相似於AndFix的接入方式;一種就是gradle的方式。安全

考慮早期使用Andfix的app應該挺多的,以及不少人對gradle的相關配置仍是以爲比較繁瑣的,下面對兩種方式都介紹下。微信

(1)命令行接入

接入以前咱們先考慮下,接入的話,正常須要的前提(開啓混淆的狀態)。

  • 對於API

    通常來講,咱們接入熱修庫,會在Application#onCreate中進行一下初始化操做。而後在某個地方去調用相似loadPatch這樣的API去加載patch文件。

  • 對於patch的生成

    簡單的方式就是經過兩個apk作對比而後生成;須要注意的是:兩個apk作對比,須要的前提條件,第二次打包混淆所使用的mapping文件應該和線上apk是一致的。

最後就是看看這個項目有沒有須要配置混淆;

有了大體的概念,咱們就基本瞭解命令行接入tinker,大體須要哪些步驟了。

依賴引入

dependencies {
     // ...
    //可選,用於生成application類
    provided('com.tencent.tinker:tinker-android-anno:1.7.7')
    //tinker的核心庫
    compile('com.tencent.tinker:tinker-android-lib:1.7.7')
}複製代碼

順便加一下簽名的配置:

android{
  //...
    signingConfigs {
        release {
            try {
                storeFile file("release.keystore")
                storePassword "testres"
                keyAlias "testres"
                keyPassword "testres"
            } catch (ex) {
                throw new InvalidUserDataException(ex.toString())
            }
        }
    }

    buildTypes {
        release {
            minifyEnabled true
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
            minifyEnabled true
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}複製代碼

文末會有demo的下載地址,能夠直接參考build.gradle文件,不用擔憂這些簽名文件去哪找。

API引入

API主要就是初始化和loadPacth。

正常狀況下,咱們會考慮在Application的onCreate中去初始化,不過tinker推薦下面的寫法:

@DefaultLifeCycle(application = ".SimpleTinkerInApplication",
        flags = ShareConstants.TINKER_ENABLE_ALL,
        loadVerifyFlag = false)
public class SimpleTinkerInApplicationLike extends ApplicationLike {
    public SimpleTinkerInApplicationLike(Application application, int tinkerFlags, boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime, long applicationStartMillisTime, Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
    }

    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        TinkerInstaller.install(this);
    }
}複製代碼

ApplicationLike經過名字你可能會猜,並不是是Application的子類,而是一個相似Application的類。

tinker建議編寫一個ApplicationLike的子類,你能夠當成Application去使用,注意頂部的註解:@DefaultLifeCycle,其application屬性,會在編譯期生成一個SimpleTinkerInApplication類。

因此,雖然咱們這麼寫了,可是實際上Application會在編譯期生成,因此AndroidManifest.xml中是這樣的:

<application
        android:name=".SimpleTinkerInApplication"
        .../>複製代碼

編寫若是報紅,能夠build下。

這樣其實也能猜出來,這個註解背後有個Annotation Processor在作處理,若是你沒了解過,能夠看下:

經過該文會對一個編譯時註解的運行流程和基本API有必定的掌握,文中也會對tinker該部分的源碼作解析。

上述,就完成了tinker的初始化,那麼調用loadPatch的時機,咱們直接在Activity中添加一個Button設置:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public void loadPatch(View view) {
        TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(),
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed.apk");
    }
}複製代碼

咱們會將patch文件直接push到sdcard根目錄;

因此必定要注意:添加SDCard權限,若是你是6.x以上的系統,本身添加上受權代碼,或者手動在設置頁面打開SDCard讀寫權限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />複製代碼

除以之外,有個特殊的地方就是tinker須要在AndroidManifest.xml中指定TINKER_ID。

<application>
  <meta-data android:name="TINKER_ID" android:value="tinker_id_6235657" /> //... </application>複製代碼

到此API相關的就結束了,剩下的就是考慮patch如何生成。

patch生成

tinker提供了patch生成的工具,源碼見:tinker-patch-cli,打成一個jar就可使用,而且提供了命令行相關的參數以及文件。

命令行以下:

java -jar tinker-patch-cli-1.7.7.jar -old old.apk -new new.apk -config tinker_config.xml -out output複製代碼

須要注意的就是tinker_config.xml,裏面包含tinker的配置,例如簽名文件等。

這裏咱們直接使用tinker提供的簽名文件,因此不須要作修改,不過裏面有個Application的item修改成與本例一致:

<loader value="com.zhy.tinkersimplein.SimpleTinkerInApplication"/>複製代碼

大體的文件結構以下:

能夠在tinker-patch-cli中提取,或者直接下載文末的例子。

上述介紹了patch生成的命令,最後須要注意的就是,在第一次打出apk的時候,保留下生成的mapping文件,在/build/outputs/mapping/release/mapping.txt

能夠copy到與proguard-rules.pro同目錄,同時在第二次打修復包的時候,在proguard-rules.pro中添加上:

-applymapping mapping.txt複製代碼

保證後續的打包與線上包使用的是同一個mapping文件。

tinker自己的混淆相關配置,能夠參考:

若是,你對該部分描述不瞭解,能夠直接查看源碼便可。

測試

首先隨便生成一個apk(API、混淆相關已經按照上述引入),安裝到手機或者模擬器上。

而後,copy出mapping.txt文件,設置applymapping,修改代碼,再次打包,生成new.apk。

兩次的apk,能夠經過命令行指令去生成patch文件。

若是你下載本例,命令須要在[該目錄]下執行。

最終會在output文件夾中生成產物:

咱們直接將patch_signed.apk push到sdcard,點擊loadpatch,必定要觀察命令行是否成功。

本例修改了title。

點擊loadPatch,觀察log,若是成功,應用默認爲重啓,而後再次啓動便可達到修復效果。

到這裏命令行的方式就介紹完了,和Andfix的接入的方式基本上是同樣的。

值得注意的是:該例僅展現了基本的接入,對於tinker的各類配置信息,仍是須要去讀tinker的文檔(若是你肯定要使用)tinker-wiki

(2)gradle接入

gradle接入的方式應該算是主流的方式,因此tinker也直接給出了例子,單獨將該tinker-sample-android以project方式引入便可。

引入以後,能夠查看其接入API的方式,以及相關配置。

在你每次build時,會在build/bakApk下生成本地打包的apk,R文件,以及mapping文件。

若是你須要生成patch文件,能夠經過:

./gradlew tinkerPatchRelease  // 或者 ./gradlew tinkerPatchDebug複製代碼

生成。

生成目錄爲:build/outputs/tinkerPatch

須要注意的是,須要在app/build.gradle中設置相比較的apk(即old.apk,本次爲new.apk),

ext {
    tinkerEnabled = true
    //old apk file to build patch apk
    tinkerOldApkPath = "${bakPath}/old.apk"
    //proguard mapping file to build patch apk
    tinkerApplyMappingPath = "${bakPath}/old-mapping.txt"
}複製代碼

提供的例子,基本上展現了tinker的自定義擴展的方式,具體還能夠參考:

因此,若是你使用命令行方式接入,也不要忘了學習下其支持哪些擴展。

3、Application是如何編譯時生成的

從註釋和命名上看:

//可選,用於生成application類
provided('com.tencent.tinker:tinker-android-anno:1.7.7')複製代碼

明顯是該庫,其結構以下:

典型的編譯時註解的項目,源碼見tinker-android-anno

入口爲com.tencent.tinker.anno.AnnotationProcessor,能夠在該services/javax.annotation.processing.Processor文件中找處處理類全路徑。

再次建議,若是你不瞭解,簡單閱讀下Android 如何編寫基於編譯時註解的項目該文。

直接看AnnotationProcessor的process方法:

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    processDefaultLifeCycle(roundEnv.getElementsAnnotatedWith(DefaultLifeCycle.class));
    return true;
}複製代碼

直接調用了processDefaultLifeCycle:

private void processDefaultLifeCycle(Set<? extends Element> elements) {
        // 被註解DefaultLifeCycle標識的對象
        for (Element e : elements) {
             // 拿到DefaultLifeCycle註解對象
            DefaultLifeCycle ca = e.getAnnotation(DefaultLifeCycle.class);

            String lifeCycleClassName = ((TypeElement) e).getQualifiedName().toString();
            String lifeCyclePackageName = lifeCycleClassName.substring(0, lifeCycleClassName.lastIndexOf('.'));
            lifeCycleClassName = lifeCycleClassName.substring(lifeCycleClassName.lastIndexOf('.') + 1);

            String applicationClassName = ca.application();
            if (applicationClassName.startsWith(".")) {
                applicationClassName = lifeCyclePackageName + applicationClassName;
            }
            String applicationPackageName = applicationClassName.substring(0, applicationClassName.lastIndexOf('.'));
            applicationClassName = applicationClassName.substring(applicationClassName.lastIndexOf('.') + 1);

            String loaderClassName = ca.loaderClass();
            if (loaderClassName.startsWith(".")) {
                loaderClassName = lifeCyclePackageName + loaderClassName;
            }

             // /TinkerAnnoApplication.tmpl
            final InputStream is = AnnotationProcessor.class.getResourceAsStream(APPLICATION_TEMPLATE_PATH);
            final Scanner scanner = new Scanner(is);
            final String template = scanner.useDelimiter("\\A").next();
            final String fileContent = template
                .replaceAll("%PACKAGE%", applicationPackageName)
                .replaceAll("%APPLICATION%", applicationClassName)
                .replaceAll("%APPLICATION_LIFE_CYCLE%", lifeCyclePackageName + "." + lifeCycleClassName)
                .replaceAll("%TINKER_FLAGS%", "" + ca.flags())
                .replaceAll("%TINKER_LOADER_CLASS%", "" + loaderClassName)
                .replaceAll("%TINKER_LOAD_VERIFY_FLAG%", "" + ca.loadVerifyFlag());
                JavaFileObject fileObject = processingEnv.getFiler().createSourceFile(applicationPackageName + "." + applicationClassName);
                processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Creating " + fileObject.toUri());
          Writer writer = fileObject.openWriter();
            PrintWriter pw = new PrintWriter(writer);
            pw.print(fileContent);
            pw.flush();
            writer.close();

        }
    }複製代碼

代碼比較簡單,能夠分三部分理解:

  • 步驟1:首先找到被DefaultLifeCycle標識的Element(爲類對象TypeElement),獲得該對象的包名,類名等信息,而後經過該對象,拿到@DefaultLifeCycle對象,獲取該註解中聲明屬性的值。
  • 步驟2:讀取一個模板文件,讀取爲字符串,將各個佔位符經過步驟1中的值替代。
  • 步驟3:經過JavaFileObject將替換完成的字符串寫文件,其實就是本例中的Application對象。

咱們看一眼模板文件:

package %PACKAGE%;

import com.tencent.tinker.loader.app.TinkerApplication;

/** * * Generated application for tinker life cycle * */
public class %APPLICATION% extends TinkerApplication {

    public %APPLICATION%() {
        super(%TINKER_FLAGS%, "%APPLICATION_LIFE_CYCLE%", "%TINKER_LOADER_CLASS%", %TINKER_LOAD_VERIFY_FLAG%);
    }

}複製代碼

對應咱們的SimpleTinkerInApplicationLike

@DefaultLifeCycle(application = ".SimpleTinkerInApplication",
        flags = ShareConstants.TINKER_ENABLE_ALL,
        loadVerifyFlag = false)
public class SimpleTinkerInApplicationLike extends ApplicationLike {}複製代碼

主要就幾個佔位符:

  • 包名,若是application屬性值以點開始,則同包;不然則截取
  • 類名,application屬性值中的類名
  • %TINKER_FLAGS%對應flags
  • %APPLICATION_LIFE_CYCLE%,編寫的ApplicationLike的全路徑
  • "%TINKER_LOADER_CLASS%",這個值咱們沒有設置,實際上對應@DefaultLifeCycle的loaderClass屬性,默認值爲com.tencent.tinker.loader.TinkerLoader
  • %TINKER_LOAD_VERIFY_FLAG%對應loadVerifyFlag

因而最終生成的代碼爲:

/** * * Generated application for tinker life cycle * */
public class SimpleTinkerInApplication extends TinkerApplication {

    public SimpleTinkerInApplication() {
        super(7, "com.zhy.tinkersimplein.SimpleTinkerInApplicationLike", "com.tencent.tinker.loader.TinkerLoader", false);
    }

}複製代碼

tinker這麼作的目的,文檔上是這麼說的:

爲了減小錯誤的出現,推薦使用Annotation生成Application類。

這樣大體瞭解了Application是如何生成的。

接下來咱們大體看一下tinker的原理。

4、原理

來源於:github.com/Tencent/tin…

tinker貼了一張大體的原理圖。

能夠看出:

tinker將old.apk和new.apk作了diff,拿到patch.dex,而後將patch.dex與本機中apk的classes.dex作了合併,生成新的classes.dex,運行時經過反射將合併後的dex文件放置在加載的dexElements數組的前面。

運行時替代的原理,其實和Qzone的方案差很少,都是去反射修改dexElements。

二者的差別是:Qzone是直接將patch.dex插到數組的前面;而tinker是將patch.dex與app中的classes.dex合併後的全量dex插在數組的前面。

tinker這麼作的目的仍是由於Qzone方案中提到的CLASS_ISPREVERIFIED的解決方案存在問題;而tinker至關於換個思路解決了該問題。

接下來咱們就從代碼中去驗證該原理。

本片文章源碼分析的兩條線:

  • 應用啓動時,從默認目錄加載合併後的classes.dex
  • patch下發後,合成classes.dex至目標目錄

5、源碼分析

###(1)加載patch

加載的代碼實際上在生成的Application中調用的,其父類爲TinkerApplication,在其attachBaseContext中展轉會調用到loadTinker()方法,在該方法內部,反射調用了TinkerLoader的tryLoad方法。

@Override
public Intent tryLoad(TinkerApplication app, int tinkerFlag, boolean tinkerLoadVerifyFlag) {
    Intent resultIntent = new Intent();

    long begin = SystemClock.elapsedRealtime();
    tryLoadPatchFilesInternal(app, tinkerFlag, tinkerLoadVerifyFlag, resultIntent);
    long cost = SystemClock.elapsedRealtime() - begin;
    ShareIntentUtil.setIntentPatchCostTime(resultIntent, cost);
    return resultIntent;
}複製代碼

tryLoadPatchFilesInternal中會調用到loadTinkerJars方法:

private void tryLoadPatchFilesInternal(TinkerApplication app, int tinkerFlag, boolean tinkerLoadVerifyFlag, Intent resultIntent) {
    // 省略大量安全性校驗代碼

    if (isEnabledForDex) {
        //tinker/patch.info/patch-641e634c/dex
        boolean dexCheck = TinkerDexLoader.checkComplete(patchVersionDirectory, securityCheck, resultIntent);
        if (!dexCheck) {
            //file not found, do not load patch
            Log.w(TAG, "tryLoadPatchFiles:dex check fail");
            return;
        }
    }

    //now we can load patch jar
    if (isEnabledForDex) {
        boolean loadTinkerJars = TinkerDexLoader.loadTinkerJars(app, tinkerLoadVerifyFlag, patchVersionDirectory, resultIntent, isSystemOTA);
        if (!loadTinkerJars) {
            Log.w(TAG, "tryLoadPatchFiles:onPatchLoadDexesFail");
            return;
        }
    }
}複製代碼

TinkerDexLoader.checkComplete主要是用於檢查下發的meta文件中記錄的dex信息(meta文件,能夠查看生成patch的產物,在assets/dex-meta.txt),檢查meta文件中記錄的dex文件信息對應的dex文件是否存在,並把值存在TinkerDexLoader的靜態變量dexList中。

TinkerDexLoader.loadTinkerJars傳入四個參數,分別爲application,tinkerLoadVerifyFlag(註解上聲明的值,傳入爲false),patchVersionDirectory當前version的patch文件夾,intent,當前patch是否僅適用於art。

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static boolean loadTinkerJars(Application application, boolean tinkerLoadVerifyFlag, String directory, Intent intentResult, boolean isSystemOTA) {
        PathClassLoader classLoader = (PathClassLoader) TinkerDexLoader.class.getClassLoader();

        String dexPath = directory + "/" + DEX_PATH + "/";
        File optimizeDir = new File(directory + "/" + DEX_OPTIMIZE_PATH);

        ArrayList<File> legalFiles = new ArrayList<>();

        final boolean isArtPlatForm = ShareTinkerInternals.isVmArt();
        for (ShareDexDiffPatchInfo info : dexList) {
            //for dalvik, ignore art support dex
            if (isJustArtSupportDex(info)) {
                continue;
            }
            String path = dexPath + info.realName;
            File file = new File(path);

            legalFiles.add(file);
        }
        // just for art
        if (isSystemOTA) {
            parallelOTAResult = true;
            parallelOTAThrowable = null;
            Log.w(TAG, "systemOTA, try parallel oat dexes!!!!!");

            TinkerParallelDexOptimizer.optimizeAll(
                legalFiles, optimizeDir,
                new TinkerParallelDexOptimizer.ResultCallback() {
                }
            );

        SystemClassLoaderAdder.installDexes(application, classLoader, optimizeDir, legalFiles);
        return true;
    }複製代碼

找出僅支持art的dex,且當前patch是否僅適用於art時,並行去loadDex。

關鍵是最後的installDexes:

@SuppressLint("NewApi")
public static void installDexes(Application application, PathClassLoader loader, File dexOptDir, List<File> files) throws Throwable {

    if (!files.isEmpty()) {
        ClassLoader classLoader = loader;
        if (Build.VERSION.SDK_INT >= 24) {
            classLoader = AndroidNClassLoader.inject(loader, application);
        }
        //because in dalvik, if inner class is not the same classloader with it wrapper class.
        //it won't fail at dex2opt
        if (Build.VERSION.SDK_INT >= 23) {
            V23.install(classLoader, files, dexOptDir);
        } else if (Build.VERSION.SDK_INT >= 19) {
            V19.install(classLoader, files, dexOptDir);
        } else if (Build.VERSION.SDK_INT >= 14) {
            V14.install(classLoader, files, dexOptDir);
        } else {
            V4.install(classLoader, files, dexOptDir);
        }
        //install done
        sPatchDexCount = files.size();
        Log.i(TAG, "after loaded classloader: " + classLoader + ", dex size:" + sPatchDexCount);

        if (!checkDexInstall(classLoader)) {
            //reset patch dex
            SystemClassLoaderAdder.uninstallPatchDex(classLoader);
            throw new TinkerRuntimeException(ShareConstants.CHECK_DEX_INSTALL_FAIL);
        }
    }
}複製代碼

這裏實際上就是根據不一樣的系統版本,去反射處理dexElements。

咱們看一下V19的實現(主要我看了下本機只有個22的源碼~):

private static final class V19 {

    private static void install(ClassLoader loader, List<File> additionalClassPathEntries, File optimizedDirectory) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, InvocationTargetException, NoSuchMethodException, IOException {

        Field pathListField = ShareReflectUtil.findField(loader, "pathList");
        Object dexPathList = pathListField.get(loader);
        ArrayList<IOException> suppressedExceptions = new ArrayList<IOException>();
        ShareReflectUtil.expandFieldArray(dexPathList, "dexElements", makeDexElements(dexPathList,
            new ArrayList<File>(additionalClassPathEntries), optimizedDirectory,
            suppressedExceptions));
        if (suppressedExceptions.size() > 0) {
            for (IOException e : suppressedExceptions) {
                Log.w(TAG, "Exception in makeDexElement", e);
                throw e;
            }
        }
    }
}複製代碼
  1. 找到PathClassLoader(BaseDexClassLoader)對象中的pathList對象
  2. 根據pathList對象找到其中的makeDexElements方法,傳入patch相關的對應的實參,返回Element[]對象
  3. 拿到pathList對象中本來的dexElements方法
  4. 步驟2與步驟3中的Element[]數組進行合併,將patch相關的dex放在數組的前面
  5. 最後將合併後的數組,設置給pathList

這裏其實和Qzone的提出的方案基本是一致的。若是你之前未了解過Qzone的方案,能夠參考此文:

###(2)合成patch

這裏的入口爲:

TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(),
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed.apk");複製代碼

上述代碼會調用DefaultPatchListener中的onPatchReceived方法:

# DefaultPatchListener
@Override
public int onPatchReceived(String path) {

    int returnCode = patchCheck(path);

    if (returnCode == ShareConstants.ERROR_PATCH_OK) {
        TinkerPatchService.runPatchService(context, path);
    } else {
        Tinker.with(context).getLoadReporter().onLoadPatchListenerReceiveFail(new File(path), returnCode);
    }
    return returnCode;

}複製代碼

首先對tinker的相關配置(isEnable)以及patch的合法性進行檢測,若是合法,則調用TinkerPatchService.runPatchService(context, path);

public static void runPatchService(Context context, String path) {
    try {
        Intent intent = new Intent(context, TinkerPatchService.class);
        intent.putExtra(PATCH_PATH_EXTRA, path);
        intent.putExtra(RESULT_CLASS_EXTRA, resultServiceClass.getName());
        context.startService(intent);
    } catch (Throwable throwable) {
        TinkerLog.e(TAG, "start patch service fail, exception:" + throwable);
    }
}複製代碼

TinkerPatchService是IntentService的子類,這裏經過intent設置了兩個參數,一個是patch的路徑,一個是resultServiceClass,該值是調用Tinker.install的時候設置的,默認爲DefaultTinkerResultService.class。因爲是IntentService,直接看onHandleIntent便可,若是你對IntentService陌生,能夠查看此文:Android IntentService徹底解析 當Service遇到Handler

@Override
protected void onHandleIntent(Intent intent) {
    final Context context = getApplicationContext();
    Tinker tinker = Tinker.with(context);


    String path = getPatchPathExtra(intent);

    File patchFile = new File(path);

    boolean result;

    increasingPriority();
    PatchResult patchResult = new PatchResult();

    result = upgradePatchProcessor.tryPatch(context, path, patchResult);

    patchResult.isSuccess = result;
    patchResult.rawPatchFilePath = path;
    patchResult.costTime = cost;
    patchResult.e = e;

    AbstractResultService.runResultService(context, patchResult, getPatchResultExtra(intent));

}複製代碼

比較清晰,主要關注upgradePatchProcessor.tryPatch方法,調用的是UpgradePatch.tryPatch。ps:這裏有個有意思的地方increasingPriority(),其內部實現爲:

private void increasingPriority() {
    TinkerLog.i(TAG, "try to increase patch process priority");
    try {
        Notification notification = new Notification();
        if (Build.VERSION.SDK_INT < 18) {
            startForeground(notificationId, notification);
        } else {
            startForeground(notificationId, notification);
            // start InnerService
            startService(new Intent(this, InnerService.class));
        }
    } catch (Throwable e) {
        TinkerLog.i(TAG, "try to increase patch process priority error:" + e);
    }
}複製代碼

若是你對「保活」這個話題比較關注,那麼對這段代碼必定不陌生,主要是利用系統的一個漏洞來啓動一個前臺Service。若是有興趣,能夠參考此文:關於 Android 進程保活,你所須要知道的一切

下面繼續回到tryPatch方法:

# UpgradePatch
@Override
public boolean tryPatch(Context context, String tempPatchPath, PatchResult patchResult) {
    Tinker manager = Tinker.with(context);

    final File patchFile = new File(tempPatchPath);

    //it is a new patch, so we should not find a exist
    SharePatchInfo oldInfo = manager.getTinkerLoadResultIfPresent().patchInfo;
    String patchMd5 = SharePatchFileUtil.getMD5(patchFile);

    //use md5 as version
    patchResult.patchVersion = patchMd5;
    SharePatchInfo newInfo;

    //already have patch
    if (oldInfo != null) {
        newInfo = new SharePatchInfo(oldInfo.oldVersion, patchMd5, Build.FINGERPRINT);
    } else {
        newInfo = new SharePatchInfo("", patchMd5, Build.FINGERPRINT);
    }

    //check ok, we can real recover a new patch
    final String patchDirectory = manager.getPatchDirectory().getAbsolutePath();
    final String patchName = SharePatchFileUtil.getPatchVersionDirectory(patchMd5);
    final String patchVersionDirectory = patchDirectory + "/" + patchName;

    //copy file
    File destPatchFile = new File(patchVersionDirectory + "/" + SharePatchFileUtil.getPatchVersionFile(patchMd5));
    // check md5 first
    if (!patchMd5.equals(SharePatchFileUtil.getMD5(destPatchFile))) {
        SharePatchFileUtil.copyFileUsingStream(patchFile, destPatchFile);
    }

    //we use destPatchFile instead of patchFile, because patchFile may be deleted during the patch process
    if (!DexDiffPatchInternal.tryRecoverDexFiles(manager, signatureCheck, context, patchVersionDirectory, 
                destPatchFile)) {
        TinkerLog.e(TAG, "UpgradePatch tryPatch:new patch recover, try patch dex failed");
        return false;
    }

    return true;
}複製代碼

拷貝patch文件拷貝至私有目錄,而後調用DexDiffPatchInternal.tryRecoverDexFiles

protected static boolean tryRecoverDexFiles(Tinker manager, ShareSecurityCheck checker, Context context, String patchVersionDirectory, File patchFile) {
    String dexMeta = checker.getMetaContentMap().get(DEX_META_FILE);
    boolean result = patchDexExtractViaDexDiff(context, patchVersionDirectory, dexMeta, patchFile);
    return result;
}複製代碼

直接看patchDexExtractViaDexDiff

private static boolean patchDexExtractViaDexDiff(Context context, String patchVersionDirectory, String meta, final File patchFile) {
    String dir = patchVersionDirectory + "/" + DEX_PATH + "/";

    if (!extractDexDiffInternals(context, dir, meta, patchFile, TYPE_DEX)) {
        TinkerLog.w(TAG, "patch recover, extractDiffInternals fail");
        return false;
    }

    final Tinker manager = Tinker.with(context);

    File dexFiles = new File(dir);
    File[] files = dexFiles.listFiles();

    ...files遍歷執行:DexFile.loadDex
     return true;
}複製代碼

核心代碼主要在extractDexDiffInternals中:

private static boolean extractDexDiffInternals(Context context, String dir, String meta, File patchFile, int type) {
    //parse meta
    ArrayList<ShareDexDiffPatchInfo> patchList = new ArrayList<>();
    ShareDexDiffPatchInfo.parseDexDiffPatchInfo(meta, patchList);

    File directory = new File(dir);
    //I think it is better to extract the raw files from apk
    Tinker manager = Tinker.with(context);
    ZipFile apk = null;
    ZipFile patch = null;

    ApplicationInfo applicationInfo = context.getApplicationInfo();

    String apkPath = applicationInfo.sourceDir; //base.apk
    apk = new ZipFile(apkPath);
    patch = new ZipFile(patchFile);

    for (ShareDexDiffPatchInfo info : patchList) {

        final String infoPath = info.path;
        String patchRealPath;
        if (infoPath.equals("")) {
            patchRealPath = info.rawName;
        } else {
            patchRealPath = info.path + "/" + info.rawName;
        }

        File extractedFile = new File(dir + info.realName);

        ZipEntry patchFileEntry = patch.getEntry(patchRealPath);
        ZipEntry rawApkFileEntry = apk.getEntry(patchRealPath);

        patchDexFile(apk, patch, rawApkFileEntry, patchFileEntry, info, extractedFile);
    }

    return true;
}複製代碼

這裏的代碼比較關鍵了,能夠看出首先解析了meta裏面的信息,meta中包含了patch中每一個dex的相關數據。而後經過Application拿到sourceDir,其實就是本機apk的路徑以及patch文件;根據mate中的信息開始遍歷,其實就是取出對應的dex文件,最後經過patchDexFile對兩個dex文件作合併。

private static void patchDexFile( ZipFile baseApk, ZipFile patchPkg, ZipEntry oldDexEntry, ZipEntry patchFileEntry, ShareDexDiffPatchInfo patchInfo, File patchedDexFile) throws IOException {
    InputStream oldDexStream = null;
    InputStream patchFileStream = null;

    oldDexStream = new BufferedInputStream(baseApk.getInputStream(oldDexEntry));
    patchFileStream = (patchFileEntry != null ? new BufferedInputStream(patchPkg.getInputStream(patchFileEntry)) : null);

    new DexPatchApplier(oldDexStream, patchFileStream).executeAndSaveTo(patchedDexFile);

}複製代碼

經過ZipFile拿到其內部文件的InputStream,其實就是讀取本地apk對應的dex文件,以及patch中對應dex文件,對兩者的經過executeAndSaveTo方法進行合併至patchedDexFile,即patch的目標私有目錄。

至於合併算法,這裏其實才是tinker比較核心的地方,這個算法跟dex文件格式緊密關聯,若是有機會,而後我又能看懂的話,後面會單獨寫篇博客介紹。此外dodola已經有篇博客進行了介紹:

感興趣的能夠閱讀下。

好了,到此咱們就大體瞭解了tinker熱修復的原理~~

固然這裏只分析了代碼了熱修復,後續考慮分析資源以及So的熱修、核心的diff算法、以及gradle插件等相關知識~

測試demo地址:

個人微信公衆號:hongyangAndroid
(能夠給我留言你想學習的文章,支持投稿)

相關文章
相關標籤/搜索