1. 程式人生 > >[Android]騰訊Tinker熱修復框架簡單使用

[Android]騰訊Tinker熱修復框架簡單使用

前言

目前我們所知的熱修復方案有阿里的AndFix、美團的Robust以及QZone的超級補丁方案,還有本篇的Tinker,如何在我們的自開發的軟體上選用合適的方案呢?

先看看各家的框架效能對比,在作參考。


總體來說:

  1. AndFix作為native解決方案,首先面臨的是穩定性與相容性問題,更重要的是它無法實現類替換,它是需要大量額外的開發成本的;
  2. Robust相容性與成功率較高,但是它與AndFix一樣,無法新增變數與類只能用做的bugFix方案;
  3. Qzone方案可以做到釋出產品功能,但是它主要問題是插樁帶來Dalvik的效能問題,以及為了解決Art下記憶體地址問題而導致補丁包急速增大的。

可以看出,Tinker熱補丁方案既支援類、So和資源的替換,還支援了2.x-7.x平臺。我們不僅可以用做bugfix,甚至可以替代功能的釋出,況且Tinker已經在數億Android端的微信上執行使用,這個噱頭你還不用?

使用說明

Tinker提供了兩種接入方式,gradle接入和命令列接入,這裡先說明gradle的方式,這也是比較推薦的方式。

1.在專案的build.gradle中,新增tinker-patch-gradle-plugin的依賴:

buildscript {
    dependencies {
        classpath ('com.tencent.tinker:tinker-patch-gradle-plugin:1.7.10')
    }
}
2.然後在app的gradle檔案app/build.gradle,我們需要新增tinker的庫依賴以及apply tinker的gradle外掛.
dependencies {
	//可選,用於生成application類 
	provided('com.tencent.tinker:tinker-android-anno:1.7.10')
    //tinker的核心庫
    compile('com.tencent.tinker:tinker-android-lib:1.7.10') 
}
//apply tinker外掛
apply plugin: 'com.tencent.tinker.patch'

3.在/app/build.gradle中加入tinkerPatch task 指令碼,
def bakPath = file("${buildDir}/bakApk/")

ext {
    //for some reason, you may want to ignore tinkerBuild, such as instant run debug build?
    tinkerEnabled = true

    //for normal build
    //old apk file to build patch apk
    tinkerOldApkPath = "${bakPath}/app-release-0601-14-29-28.apk"
    //proguard mapping file to build patch apk
    tinkerApplyMappingPath = "${bakPath}/app-release-0601-14-29-28-mapping.txt"
    //resource R.txt to build patch apk, must input if there is resource changed
    tinkerApplyResourcePath = "${bakPath}/app-release-0601-14-29-28-R.txt"

    //only use for build all flavor, if not, just ignore this field
   // tinkerBuildFlavorDirectory = "${bakPath}/app-0526-17-40-51"
}

//這個方法其實就是定義了一個tink_id
def getSha() {
    try {
        String tinkId = "tink_id_000000000"
        if (tinkId == null) {
            throw new RuntimeException("you should add tinkeId to system path or just input test value, such as 'testTinkerId'")
        }
        return tinkId
    } catch (Exception e) {
        throw new RuntimeException("you should add tinkeId to system path or just input test value, such as 'testTinkerId'")
    }
}


def getOldApkPath() {
    return hasProperty("OLD_APK") ? OLD_APK : ext.tinkerOldApkPath
}

def getApplyMappingPath() {
    return hasProperty("APPLY_MAPPING") ? APPLY_MAPPING : ext.tinkerApplyMappingPath
}

def getApplyResourceMappingPath() {
    return hasProperty("APPLY_RESOURCE") ? APPLY_RESOURCE : ext.tinkerApplyResourcePath
}

def getTinkerIdValue() {
    return hasProperty("TINKER_ID") ? TINKER_ID : getSha()
}

def buildWithTinker() {
    return hasProperty("TINKER_ENABLE") ? TINKER_ENABLE : ext.tinkerEnabled
}

def getTinkerBuildFlavorDirectory() {
    return ext.tinkerBuildFlavorDirectory
}

if (buildWithTinker()) {
    apply plugin: 'com.tencent.tinker.patch'

    tinkerPatch {
        /**
         * necessary,default 'null'
         * the old apk path, use to diff with the new apk to build
         * add apk from the build/bakApk
         */
        oldApk = getOldApkPath()
        /**
         * optional,default 'false'
         * there are some cases we may get some warnings
         * if ignoreWarning is true, we would just assert the patch process
         * case 1: minSdkVersion is below 14, but you are using dexMode with raw.
         *         it must be crash when load.
         * case 2: newly added Android Component in AndroidManifest.xml,
         *         it must be crash when load.
         * case 3: loader classes in dex.loader{} are not keep in the main dex,
         *         it must be let tinker not work.
         * case 4: loader classes in dex.loader{} changes,
         *         loader classes is ues to load patch dex. it is useless to change them.
         *         it won't crash, but these changes can't effect. you may ignore it
         * case 5: resources.arsc has changed, but we don't use applyResourceMapping to build
         */
        ignoreWarning = false

        /**
         * optional,default 'true'
         * whether sign the patch file
         * if not, you must do yourself. otherwise it can't check success during the patch loading
         * we will use the sign config with your build type
         */
        useSign = true

        /**
         * optional,default 'true'
         * whether use tinker to build
         */
        tinkerEnable = buildWithTinker()

        /**
         * Warning, applyMapping will affect the normal android build!
         */
        buildConfig {
            /**
             * optional,default 'null'
             * if we use tinkerPatch to build the patch apk, you'd better to apply the old
             * apk mapping file if minifyEnabled is enable!
             * Warning:
             * you must be careful that it will affect the normal assemble build!
             */
            applyMapping = getApplyMappingPath()
            /**
             * optional,default 'null'
             * It is nice to keep the resource id from R.txt file to reduce java changes
             */
            applyResourceMapping = getApplyResourceMappingPath()

            /**
             * necessary,default 'null'
             * because we don't want to check the base apk with md5 in the runtime(it is slow)
             * tinkerId is use to identify the unique base apk when the patch is tried to apply.
             * we can use git rev, svn rev or simply versionCode.
             * we will gen the tinkerId in your manifest automatic
             */
            tinkerId = getTinkerIdValue()

            /**
             * if keepDexApply is true, class in which dex refer to the old apk.
             * open this can reduce the dex diff file size.
             */
            keepDexApply = false

            /**
             * optional, default 'false'
             * Whether tinker should treat the base apk as the one being protected by app
             * protection tools.
             * If this attribute is true, the generated patch package will contain a
             * dex including all changed classes instead of any dexdiff patch-info files.
             */
            isProtectedApp = false
        }

        dex {
            /**
             * optional,default 'jar'
             * only can be 'raw' or 'jar'. for raw, we would keep its original format
             * for jar, we would repack dexes with zip format.
             * if you want to support below 14, you must use jar
             * or you want to save rom or check quicker, you can use raw mode also
             */
            dexMode = "jar"

            /**
             * necessary,default '[]'
             * what dexes in apk are expected to deal with tinkerPatch
             * it support * or ? pattern.
             */
            pattern = ["classes*.dex",
                       "assets/secondary-dex-?.jar"]
            /**
             * necessary,default '[]'
             * Warning, it is very very important, loader classes can't change with patch.
             * thus, they will be removed from patch dexes.
             * you must put the following class into main dex.
             * Simply, you should add your own application {@code tinker.sample.android.SampleApplication}
             * own tinkerLoader, and the classes you use in them
             *
             */
            loader = [
                    //use sample, let BaseBuildInfo unchangeable with tinker
                    "com.tencent.tinker.loader.*",
                    "com.tencent.tinker.*",
                    "com.example.myapp.MyApplication"
            ]
        }

        lib {
            /**
             * optional,default '[]'
             * what library in apk are expected to deal with tinkerPatch
             * it support * or ? pattern.
             * for library in assets, we would just recover them in the patch directory
             * you can get them in TinkerLoadResult with Tinker
             */
            pattern = ["lib/*/*.so"]
        }

        res {
            /**
             * optional,default '[]'
             * what resource in apk are expected to deal with tinkerPatch
             * it support * or ? pattern.
             * you must include all your resources in apk here,
             * otherwise, they won't repack in the new apk resources.
             */
            pattern = ["res/*", "assets/*", "resources.arsc", "AndroidManifest.xml"]

            /**
             * optional,default '[]'
             * the resource file exclude patterns, ignore add, delete or modify resource change
             * it support * or ? pattern.
             * Warning, we can only use for files no relative with resources.arsc
             */
            ignoreChange = ["assets/sample_meta.txt"]

            /**
             * default 100kb
             * for modify resource, if it is larger than 'largeModSize'
             * we would like to use bsdiff algorithm to reduce patch file size
             */
            largeModSize = 100
        }

        packageConfig {
            /**
             * optional,default 'TINKER_ID, TINKER_ID_VALUE' 'NEW_TINKER_ID, NEW_TINKER_ID_VALUE'
             * package meta file gen. path is assets/package_meta.txt in patch file
             * you can use securityCheck.getPackageProperties() in your ownPackageCheck method
             * or TinkerLoadResult.getPackageConfigByName
             * we will get the TINKER_ID from the old apk manifest for you automatic,
             * other config files (such as patchMessage below)is not necessary
             */
            configField("TINKER_ID", getSha())
            configField("app_name", "MyApp")
            configField("patchMessage", "這是一個測試");
            /**
             * just a sample case, you can use such as sdkVersion, brand, channel...
             * you can parse it in the SamplePatchListener.
             * Then you can use patch conditional!
             */
            configField("platform", "all")
            /**
             * patch version via packageConfig
             */
            configField("patchVersion", "1.0")
        }
        //or you can add config filed outside, or get meta value from old apk
        //project.tinkerPatch.packageConfig.configField("test1", project.tinkerPatch.packageConfig.getMetaDataFromOldApk("Test"))
        //project.tinkerPatch.packageConfig.configField("test2", "sample")

        /**
         * if you don't use zipArtifact or path, we just use 7za to try
         */
        sevenZip {
            /**
             * optional,default '7za'
             * the 7zip artifact path, it will use the right 7za with your platform
             */
            zipArtifact = "com.tencent.mm:SevenZip:1.1.10"
            /**
             * optional,default '7za'
             * you can specify the 7za path yourself, it will overwrite the zipArtifact value
             */
//        path = "/usr/local/bin/7za"
        }
    }

    List<String> flavors = new ArrayList<>();
    project.android.productFlavors.each {flavor ->
        flavors.add(flavor.name)
    }
    boolean hasFlavors = flavors.size() > 0
    def date = new Date().format("MMdd-HH-mm-ss")

    /**
     * bak apk and mapping
     */
    android.applicationVariants.all { variant ->
        /**
         * task type, you want to bak
         */
        def taskName = variant.name

        tasks.all {
            if ("assemble${taskName.capitalize()}".equalsIgnoreCase(it.name)) {

                it.doLast {
                    copy {
                        def fileNamePrefix = "${project.name}-${variant.baseName}"
                        def newFileNamePrefix = hasFlavors ? "${fileNamePrefix}" : "${fileNamePrefix}-${date}"

                        def destPath = hasFlavors ? file("${bakPath}/${project.name}-${date}/${variant.flavorName}") : bakPath
                        from variant.outputs.outputFile
                        into destPath
                        rename { String fileName ->
                            fileName.replace("${fileNamePrefix}.apk", "${newFileNamePrefix}.apk")
                        }

                        from "${buildDir}/outputs/mapping/${variant.dirName}/mapping.txt"
                        into destPath
                        rename { String fileName ->
                            fileName.replace("mapping.txt", "${newFileNamePrefix}-mapping.txt")
                        }

                        from "${buildDir}/intermediates/symbols/${variant.dirName}/R.txt"
                        into destPath
                        rename { String fileName ->
                            fileName.replace("R.txt", "${newFileNamePrefix}-R.txt")
                        }
                    }
                }
            }
        }
    }
    project.afterEvaluate {
        //sample use for build all flavor for one time
        if (hasFlavors) {
            task(tinkerPatchAllFlavorRelease) {
                group = 'tinker'
                def originOldPath = getTinkerBuildFlavorDirectory()
                for (String flavor : flavors) {
                    def tinkerTask = tasks.getByName("tinkerPatch${flavor.capitalize()}Release")
                    dependsOn tinkerTask
                    def preAssembleTask = tasks.getByName("process${flavor.capitalize()}ReleaseManifest")
                    preAssembleTask.doFirst {
                        String flavorName = preAssembleTask.name.substring(7, 8).toLowerCase() + preAssembleTask.name.substring(8, preAssembleTask.name.length() - 15)
                        project.tinkerPatch.oldApk = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-release.apk"
                        project.tinkerPatch.buildConfig.applyMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-release-mapping.txt"
                        project.tinkerPatch.buildConfig.applyResourceMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-release-R.txt"
                    }
                }
            }

            task(tinkerPatchAllFlavorDebug) {
                group = 'tinker'
                def originOldPath = getTinkerBuildFlavorDirectory()
                for (String flavor : flavors) {
                    def tinkerTask = tasks.getByName("tinkerPatch${flavor.capitalize()}Debug")
                    dependsOn tinkerTask
                    def preAssembleTask = tasks.getByName("process${flavor.capitalize()}DebugManifest")
                    preAssembleTask.doFirst {
                        String flavorName = preAssembleTask.name.substring(7, 8).toLowerCase() + preAssembleTask.name.substring(8, preAssembleTask.name.length() - 13)
                        project.tinkerPatch.oldApk = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-debug.apk"
                        project.tinkerPatch.buildConfig.applyMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-debug-mapping.txt"
                        project.tinkerPatch.buildConfig.applyResourceMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-debug-R.txt"
                    }
                }
            }
        }
    }
}

注意,minifyEnabled一定要設定為true,別忘了設定tinkerId,在getSha方法裡可以先寫死。

程式碼裡我們要做點什麼呢?我需要先自定義Application類,因為引入了Tinker,所以原來的MyApplication必須改造。

程式啟動時會載入預設的Application類,這導致我們補丁包是無法對它做修改了。如何規避?在這裡我們並沒有使用類似InstantRun hook Application的方式,而是通過程式碼框架的方式來避免,這也是為了儘量少的去反射,提升框架的相容性。這裡我們要實現的是完全將原來的Application類隔離起來,即其他任何類都不能再引用我們自己的Application。我們需要做的其實是以下幾個工作:

  1. 將我們自己Application類以及它的繼承類的所有程式碼拷貝到自己的ApplicationLike繼承類中,例如MyApplicationLike。你也可以直接將自己的Application改為繼承ApplicationLike;
  2. Application的attachBaseContext方法實現要單獨移動到onBaseContextAttached中;
  3. 對ApplicationLike中,引用application的地方改成getApplication();
  4. 對其他引用Application或者它的靜態物件與方法的地方,改成引用ApplicationLike的靜態物件與方法;

我的demo中原來是自定義的MyApplication,現在必須把之前的Application中定義的變數轉移到自定義的ApplicationLike中去,然後自動生成MyApplication,這裡使用Annotation生成Application類(推薦)。

MyApplicationLike.java

package com.example.myapp;

import android.app.Application;
import android.content.Context;
import android.content.Intent;

import com.example.myapp.db.dao.DaoMaster;
import com.example.myapp.db.dao.DaoSession;
import com.example.myapp.event.MyEventBusIndex;
import com.jan.lib.BusPoster;
import com.tencent.tinker.anno.DefaultLifeCycle;
import com.tencent.tinker.lib.tinker.TinkerInstaller;
import com.tencent.tinker.loader.app.DefaultApplicationLike;
import com.tencent.tinker.loader.shareutil.ShareConstants;

import org.greenrobot.greendao.database.Database;

/**
 * Created by Jan on 2017/5/25.
 */
@DefaultLifeCycle(
        application = ".MyApplication",
        flags = ShareConstants.TINKER_ENABLE_ALL, ////tinkerFlags, tinker支援的型別,dex,library,還是全部都支援!
        loaderClass = "com.tencent.tinker.loader.TinkerLoader",//loaderClassName, 我們這裡使用預設即可!
        loadVerifyFlag = false)    //tinkerLoadVerifyFlag
public class MyApplicationLike extends DefaultApplicationLike {

    public static final boolean ENCRYPTED = false;
    private DaoSession mDaoSession;
    public static Context mContext;

    public MyApplicationLike(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);
        MyApplication application = (MyApplication) getApplication();
        BusPoster.registerSubIndex(new MyEventBusIndex());
        mContext =application.getApplicationContext();
        registerDaoComp();
    }

    private void registerDaoComp(){
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(mContext,ENCRYPTED ? "app-db-encrypted" : "app-db");
        Database db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb();
        mDaoSession = new DaoMaster(db).newSession();
    }

    public DaoSession getDaoSession(){
        return mDaoSession;
    }

}

AndroidMnaifest,xml裡的android:name=".MyApplication" 這個是自動生成的哦~

為了方便測試效果,我們在demo的測試Activity中寫入這樣的邏輯:加入一個按鈕A,用於執行載入修復補丁包,以及展示一段文字,為了和加入補丁後的程式碼進行比較,用來判斷是否有效。

因為這裡載入補丁包勢必要有讀取檔案的許可權:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Tinker tinker = Tinker.with(getApplicationContext());
        //判斷是否載入了補丁
        if(tinker.isTinkerLoaded()){
            Toast.makeText(this,"patch is loaded",Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(this,"patch is not loaded",Toast.LENGTH_SHORT).show();
        }
        //用來載入補丁包的按鈕
        btn2 = (Button) findViewById(R.id.button2);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //adb push ./app/build/outputs/tinkerPatch/debug/patch_signed_7zip.apk /storage/sdcard0/
                TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed_7zip.apk");

            }
        });
        //關閉APP的按鈕
        btn3 = (Button) findViewById(R.id.button3);
        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareTinkerInternals.killAllOtherProcess(getApplicationContext());
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        });

好了,程式碼基本很簡單。下面講講如何打包。

4.我們這裡模擬打正式釋出的包,先執行gradle上述的方法中的assembleRelease指令碼


我們這裡生成了基準包,在build/bakApk/下的。。。apk檔案和mapping檔案,R字典檔案配置到如圖的區域中。這一步驟可不能忘了。這個基準包apk我們是經過混淆過的,我們把這個app-release-xxx.apk,先安裝到手機上。


接著修改 Activity中的文字展示的程式碼,然後開始生成補丁包,執行tinkerPatchRelease


這會兒在app\build\outputs\tinkerPatch\release目錄下找到補丁包patch_signed_7zip.apk,然後push到手機sd卡下,準備載入動作。

執行命令adb push ./app/build/outputs/tinkerPatch/release/patch_signed_7zip.apk /storage/sdcard0/ 即可。

再開啟我們剛開始裝的app,點選執行載入補丁功能,如果成功,將會自動關閉下次啟動後,發現展示的文字是最新修改過的。如果你失敗了,那得看看日誌,找找哪裡出了問題。