Android 熱更新 Tinker 整合配置【詳細】

ppjunSpirit發表於2018-02-26

Tinker簡單接入

Tinker 是微信官方的 Android 熱補丁解決方案,它支援動態下發程式碼、So 庫以及資源,讓應用能夠在不需要重新安裝的情況下實現更新。

不足之處

  1. Tinker 不支援修改 AndroidManifest.xml,Tinker 不支援新增四大元件 (1.9.0 支援新增非 export 的 Activity);
  2. 由於 Google Play 的開發者條款限制,不建議在 GP 渠道動態更新程式碼;
  3. 在 Android N 上,補丁對應用啟動時間有輕微的影響;
  4. 不支援部分三星 android-21 機型,載入補丁時會主動丟擲"TinkerRuntimeException:checkDexInstall failed";
  5. 對於資源替換,不支援修改 remoteView。例如 transition 動畫,notification icon 以及桌面圖示。

優點

  1. 開源,免費;
  2. Tinker 已執行在微信的數億 Android 裝置上使用了

####1. 新增Tinker外掛和庫

在root專案根目錄的build.gradle下

 classpath 'com.tencent.tinker:tinker-patch-gradle-plugin:1.9.1'
複製程式碼

在app專案的build.gradle下,從Tinkerdemo中看出以gradle外掛版本分別用了implementation和compile,還要記得dex分包

 dependencies {
 if (is_gradle_3()) {
     implementation("com.tencent.tinker:tinker-android-lib:1.9.1") { changing = true }
     annotationProcessor("com.tencent.tinker:tinker-android-anno:1.9.1") { changing = true }
     compileOnly("com.tencent.tinker:tinker-android-anno:1.9.1") { changing = true }
     compile "com.android.support:multidex:1.0.1"

 }else{
     compile "com.android.support:multidex:1.0.1"
     provided('com.tencent.tinker:tinker-android-anno:1.9.1')
     compile('com.tencent.tinker:tinker-android-lib:1.9.1') 
     
 }
複製程式碼

2. 開啟dex分包和大專案模式

defaultConfig {
      multiDexEnabled true
}

dexOptions {
        jumboMode = true
        maxProcessCount 4
        javaMaxHeapSize "2g"
    }
複製程式碼

3. 新增任務

這時候需要定義tinkerid(這裡你可以用到gitSha或者版本號.補丁號來定義)oldapkname,mapping,resourse.arsc等變數,把下面這一段複製到app/build.gradle

//定義一個存放oldapk的資料夾
def bakPath = file("${buildDir}/bakApk/")


ext {
    //開放專案階段設定為false,等專案要上架了再設定為true
    tinkerEnabled = true

    //for normal build
    //就是基礎包,就是你要修復上架的應用的apk,tinker會根據這個apk名字去打補丁包
    tinkerOldApkPath = "${bakPath}/app-debug-1018-17-32-47.apk"
    //基礎包的混淆檔案
    tinkerApplyMappingPath = "${bakPath}/app-debug-1018-17-32-47-mapping.txt"
    //基礎包的R.txt資源索引檔案
    tinkerApplyResourcePath = "${bakPath}/app-debug-1018-17-32-47-R.txt"
    //如果你要編譯多個不同版本的apk,否則忽略它
    //tinkerBuildFlavorDirectory = "${bakPath}/app-1018-17-32-47"
}
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 : gitSha()
}

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
         */
         //預設不忽略警告,當設定為true,注意以下情況時會退出打補丁包或者打補丁失敗
            //1.最小sdk版本小於14,你用了raw就gg了
            //2.加了新的四大元件(1.9.0可以加入非export的Activity)到Android配置檔案
            //3.tinker的dex沒打包進main.dex,tinker就不工作了
            //4.tinker類是用來載入補丁dex的,改變他們是沒用的,雖然不會崩潰,但是改變是無效的,可以忽略它
            //5.資源修改了,沒用新的mapping.txt去編譯
        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
         */
            //簽名補丁apk,否則會檢驗補丁apk失敗,要和基礎包apk簽名一樣
        useSign = true

        /**
         * optional,default 'true'
         * whether use tinker to build
         */
            //tinker開關
        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!
             */
            //讓補丁apk和基礎包apkproguard混淆檔案保持一致,可以減少補丁包體積
            applyMapping = getApplyMappingPath()
            /**
             * optional,default 'null'
             * It is nice to keep the resource id from R.txt file to reduce java changes
             */
                //讓補丁包apk和基礎包的資源R檔案保持一致,維持資源id的分配,
            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一樣,才能打入補丁,我們會把tinkerid編譯到androidmanifest檔案
            tinkerId = getTinkerIdValue()

            /**
             * if keepDexApply is true, class in which dex refer to the old apk.
             * open this can reduce the dex diff file size.
             */
                //會用diff加工補丁包dex減少dex體積
            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.
             */
                //是否加固apk,用於360,樂固加固後的apk才開啟
            isProtectedApp = false

            /**
             * optional, default 'false'
             * Whether tinker should support component hotplug (add new component dynamically).
             * If this attribute is true, the component added in new apk will be available after
             * patch is successfully loaded. Otherwise an error would be announced when generating patch
             * on compile-time.
             *
             * <b>Notice that currently this feature is incubating and only support NON-EXPORTED Activity</b>
             */
                //要不要更新activity,tinker1.9.+才有的
            supportHotplugComponent = 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
             */
            //這裡有jar和raw模式給你選,raw模式就是保持dex格式,jar就是重新把多個dex打包進jar
           //你想支援14-就一定要用jar,raw省略了md5驗證和減少體積。但是我們還是用jar吧不檢查md5
            dexMode = "jar"

            /**
             * necessary,default '[]'
             * what dexes in apk are expected to deal with tinkerPatch
             * it support * or ? pattern.
             */
                //apk哪些要用tinkerpatch處理
            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
             *
             */
                //保持哪些類不會被修改,比如讓basebuildinfo打補丁的時候不會被改變,
            loader = [
                    //use sample, let BaseBuildInfo unchangeable with tinker
                    "tinker.sample.android.app.BaseBuildInfo"
            ]
        }

        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
             */
            //要處理so檔案
            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
             */
                //如果資源大於100就用bsdiff資源來減小補丁包體積
            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
             */
            //定義一些變數可以用tinker.tinkerLoadResultIfPresent.getPackageConfigByName來獲取
            configField("patchMessage", "tinker is sample to use")
            /**
             * 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
             */
            //7zip來壓縮你的補丁apk
            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.first().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"
                    }

                }
            }
        }
    }
}

複製程式碼

加入TinkerDemo裡面的類

image.png

把tinkerdemo中的crash log reporter service 和util複製到你的專案,還要註冊sampleresultservice的服務

SampleUncaughtExceptionHandler捕抓全域性異常類
MyLogImp控制日誌輸出類
SamplePatchListener 檢測補丁md5的類
SamplePatchReporter 補丁升級,異常,打斷的回撥
SampleTinkerReport 集中管理狀態碼
SampleResultService 處理載入補丁結果,開啟服務在後臺結束程式
TinkerManager 初始化全域性異常,安裝補丁的類
Utils 工具類判斷xposed是否存在 rom空間,是否息屏
複製程式碼

替換ApplicationLike

新建一個TinkerApplicationLike 繼承DefaultApplicationLike

@SuppressWarnings("unused")
@DefaultLifeCycle(application = "你原來的applciation名字",
                  flags = ShareConstants.TINKER_ENABLE_ALL,
                  loadVerifyFlag = false)
public class SampleApplicationLike extends DefaultApplicationLike {
    private static final String TAG = "Tinker.SampleApplicationLike";

    public SampleApplicationLike(Application application, int tinkerFlags, boolean tinkerLoadVerifyFlag,
                                 long applicationStartElapsedTime, long applicationStartMillisTime, Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
    }

    /**
     * install multiDex before install tinker
     * so we don't need to put the tinker lib classes in the main dex
     *
     * @param base
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        //you must install multiDex whatever tinker is installed!
        //開啟dex分包
        MultiDex.install(base);

        SampleApplicationContext.application = getApplication();
        SampleApplicationContext.context = getApplication();
        TinkerManager.setTinkerApplicationLike(this);

        TinkerManager.initFastCrashProtect();
        //should set before tinker is installed
        TinkerManager.setUpgradeRetryEnable(true);

        //optional set logIml, or you can use default debug log
        //debug的時候可以輸出log,發release版本去掉這句
        TinkerInstaller.setLogIml(new MyLogImp());

        //installTinker after load multiDex
        //or you can put com.tencent.tinker.** to main dex
        //安裝tinker dex到主dex
        TinkerManager.installTinker(this);
        Tinker tinker = Tinker.with(getApplication());
        
        //把你原來Application的attachbasecontext搬運到這裡
    }
 @Override
    public void onCreate() {
        super.onCreate();
     //把你原來Application的oncreate搬運到這裡
    }
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks callback) {
        getApplication().registerActivityLifecycleCallbacks(callback);
    }

}

複製程式碼

TinkerInstaller方法

打上補丁

TinkerInstaller.onReceiveUpgradePatch(this@TestUI, outFile.absolutePath)
//outFile這裡是sd卡patch.apk的路徑
Tinker.with(getApplicationContext()).cleanPatch();
//刪除全部補丁
Tinker.with(getApplicationContext()).cleanPatchByVersion(版本號)
//刪除某個版本號的補丁
ShareTinkerInternals.killAllOtherProcess(getApplicationContext());
//終止其他程式
android.os.Process.killProcess(android.os.Process.myPid());
//終止主程式,打上補丁後,重啟app才生效
複製程式碼

流程是在閃屏介面開啟服務去請求補丁包,然後儲存到sd卡,呼叫onReceiveUpgradePatch載入補丁。

打一個debug基準包。

呼叫build-build apks或者./gradlew assemblesDebug在app/build/bakApk/生成以打包時間為名稱的apk,然後我們重新命名為app-debug-1018-17-32-47.apk,用手機安裝這個apk包

修改內容比如把輸出內容改變一下。

print.setOnClickListener {
    ToastUtil.showTipMessage(this@TestUI, "hello world by tinker by tinker")
}
複製程式碼

在終端執行./gradlew tinkerPatchDebug,執行成功後會在app/build/outputs/apk/tinkerPatch/debug/看到以下補丁包,我們選擇patch_sign_7zip.apk.來載入。

patch_signed.apk 簽名補丁包

patch_signed_7zip.apk 簽名壓縮後的補丁包

Patch_unsigned.apk 未簽名的補丁包

問題

在執行tinkerPatchDebug的時候,報出warnning manifest is changed . 錯誤說manifest檔案被修改了。然後在tinker的issue裡面找到 用三角形的run的apk的androidmanifest。xml裡面的application標籤會加入 android:testOnly="true"屬性。 而tinkerPatchDebug打的包沒有這個屬性 所以manifest檔案不一致。

後話

因為tinker要用到後臺管理補丁,發放補丁。下一篇文章會介紹整合bugly管理髮放補丁。

備註

http://blog.csdn.net/pigwithbadguy/article/details/53536408 這篇文章介紹了tinkerid app的版本號和補丁的版本號。 就是基準包和補丁包的tinkerid要保持一致。tinkerid一般與apk版本號一致。一個基準包可以載入多個補丁包。(就是說基準包可以不用安裝舊的補丁包,直接安裝最新的補丁包),當應用釋出第二版本要升級tinkerid。

相關文章