【总结】Tinker热修复接入

项目越做越大,总是省不了热修复这个点,毕竟测试人员再仔细,还是有几率漏掉bug,或者压根就是产品抽风,已经上线的东西还非要做些更改。总之,热修复是所有程序员绕不过去的一个点。
还好已经有大厂提前帮我们铺好了这条路,不用费太多工夫。

我们的项目选择接入腾讯的Tinker,毕竟有的用户可能没钱逛淘宝(阿里的 AndFix),用不到美团(美团的 Robust),但他们都会用微信,微信作为社交软件,占领了大部分用户的手机。
这篇文字主要是把我集成Tinker的过程展示出来,并且记录下我遇到的几个坑,具体深入的原理以及细节,可以去Tinker的Github查阅相关资料。

对了,篇幅量看着挺大,其实没多少东西,都是复制的代码,所以请放心食用,很简单的。

1,添加依赖以及

打开Tinker的Github,像往常添加三方库那样,将依赖添加到项目中。
project的build.gradle

dependencies {
    ...
    classpath('com.tencent.tinker:tinker-patch-gradle-plugin:1.9.1')
    ...
}

app的build.gradle

dependencies {
    ...
    //可选,用于生成application类
    compileOnly 'com.tencent.tinker:tinker-android-anno:1.9.1'
    //tinker的核心库
    implementation 'com.tencent.tinker:tinker-android-lib:1.9.1'
    annotationProcessor 'com.tencent.tinker:tinker-android-anno:1.9.1'
    // 合并的时候需要
    implementation "com.android.support:multidex:1.0.3"
    ...
}

如果在Demo中添加热更新的话(没有人会把不熟练的东西直接往项目里丢吧?),记得添加SD卡读写权限,毕竟是要来读取Patch包的。



接下来配置Tinker的配置项,写在app的build.gradle中。
可以直接复制下面的代码,下面的代码基于官方Demo做了一点修改,删掉了gitSha()方法。
或者从Tinker的Demo的build.gradle中复制过来,但请记得修改官方代码中ignoreWarning = false,改为true,否则不执行热修复。

//----------------------------------tinker配置--------------------------
def bakPath = file("${buildDir}/bakApk/")

//删掉了gitSha()方法,是从git获取版本号的方法

ext {
    tinkerEnabled = true
    tinkerOldApkPath = "${bakPath}/app-debug-0424-15-02-56.apk"
    tinkerApplyMappingPath = "${bakPath}/app-debug-1018-17-32-47-mapping.txt"
    tinkerApplyResourcePath = "${bakPath}/app-debug-0424-15-02-56-R.txt"
    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()
    // 必须把TINKER_ID写死在gradle.properties中,而且删掉了gitSha()方法,是从git获取版本号的方法
    return TINKER_ID
}

def buildWithTinker() {
    return hasProperty("TINKER_ENABLE") ? Boolean.parseBoolean(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

            /**
             * 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.
             *
             * Notice that currently this feature is incubating and only support NON-EXPORTED Activity
             */
            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
             */
            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
                    "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
             */
            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("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
             */
            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 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

                        if (variant.metaClass.hasProperty(variant, 'packageApplicationProvider')) {
                            def packageAndroidArtifact = variant.packageApplicationProvider.get()
                            if (packageAndroidArtifact != null) {
                                try {
                                    from new File(packageAndroidArtifact.outputDirectory.getAsFile().get(), variant.outputs.first().apkData.outputFileName)
                                } catch (Exception e) {
                                    from new File(packageAndroidArtifact.outputDirectory, variant.outputs.first().apkData.outputFileName)
                                }
                            } else {
                                from variant.outputs.first().mainOutputFile.outputFile
                            }
                        } else {
                            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"
                        from "${buildDir}/intermediates/symbol_list/${variant.dirName}/R.txt"
                        from "${buildDir}/intermediates/runtime_symbol_list/${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"
                    }
                }
            }
        }
    }
}
//----------------------------------tinker配置--------------------------

然后还有在项目的gradle.properties中添加,同样的,有官方Demo的地址gradle.properties

TINKER_VERSION=1.9.8
TINKER_ID=1.0
# TINKER_ID是区分增量/完整包的关键变量
OLD_APK=D\:\\Java\\other\\TinkerTest\\app\\build\\bakApk\\app-debug-16-50.apk
# OLD_APK可以删除,是方便更改apk名的方法,这个下面会说到

配置基本就到这里,接下来是代码的部分。

2,代码

接下来是代码部分,首先,是生成Application,如果要使用Tinker热更新,就必须使用它生成的Application类。
此时,我们就有一个工具类,用来生成Application

@DefaultLifeCycle(
        application = "你的包名.MyApp",        //这里填写包名和你想要生成的Application类名,tinker会自动生成该类
        flags = ShareConstants.TINKER_ENABLE_ALL            
)
public class SampleApplicationLike extends DefaultApplicationLike {
    public SampleApplicationLike(Application application, int tinkerFlags, boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime, long applicationStartMillisTime, Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
    }

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

    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        MultiDex.install(base);
        TinkerInstaller.install(this);
    }
}

build项目之后,把android:name=".MyApp"写进AndroidManifest


接下来,你可以写一个你喜欢的布局,但记得留一个Button来激活热修复。

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TinkerInstaller.onReceiveUpgradePatch(getApplication().getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed");
            }
        });

此时编译,运行,前期准备工作就算完成了。
这时候运行项目点击按钮时没有任何反应的,因为增量包还没有放上去。

3,热修复部分

接下来我们准备生成增量包的部分。
到这时候,我们可以认为项目已经发布并且被用户安装(安装到测试机),假定我们现在也有个bug,需要修改button的文字。
此时切换到project视图,在如图所示目录下,能看到一个以时间戳命名的apk包,我们叫他基准包。它就是刚刚安装到手机上的那个有bug的包。

【总结】Tinker热修复接入_第1张图片
基准包.png

重要:这个包名的生成规则,在app的build.gradle中搜索"MMdd-HH-mm-ss"可以看到,此处可以修改,但是一定要保证每次生成的包名都有不同,否则可能会造成热修复无法生效的问题。

现在要通过热更新的方式对这个app进行修改,首先,要把基准包的包命复制到
app的build.gradle文件中

ext {
    ...
    tinkerOldApkPath = "${bakPath}/app-debug-0424-15-02-56.apk"//这个位置
    ...
}

如果你在gradle.properties文件中定义了OLD_APK,那就必须写在OLD_APK这个位置,不过记得把文件路径换成你自己的

OLD_APK=D\:\\Java\\other\\TinkerAgain\\app\\build\\bakApk\\app-debug-16-50.apk

我比较推荐第二种这个写法,位置好找,并且不会因为误删build.gradle代码造成其他问题
放一张图,看起来直观一些。

【总结】Tinker热修复接入_第2张图片
修改包名的位置.png

修改完成同步之后,修改Activity中的代码,比如

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TinkerInstaller.onReceiveUpgradePatch(getApplication().getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed");
            }
        });
        button.setText("修改文字");

修改刚才button中的文字,之后找到如图所示路径,双击开始生成差异包


【总结】Tinker热修复接入_第3张图片
编译差异包.png

看到BUILD SUCCESSFUL就说明成功了,此时在如图目录会生成一个差异包。

【总结】Tinker热修复接入_第4张图片
差异包位置.png

将差异包复制到桌面, 改名(我代码里写的是patch_signed),然后复制到手机根目录,点击按钮。
等待几秒之后,app会直接退出,再次打开就是热修复完成的样子了。

【总结】Tinker热修复接入_第5张图片
修改成功.png

4,要注意的地方

1,读写权限

一定要记得开SD卡读写权限,否则全部做对了,但是程序读不到差异包也不会生效。
表现出来的样子是点击按钮没反应。
跟着走下来,但是没生效的话,大概率是权限问题。

2,基准包的命名

就是在app的build.gradle中


if (buildWithTinker()) {
    ...
    def date = new Date().format("MMdd-HH-mm-ss")
    ...
}

这个时间格式会影响命名,具体来说会影响app-debug-XXX.apk中间的部分,上面也说过,这个位置可以改,但是一定要保证每次生成的包名都有不同,否则可能会造成热修复无法生效的问题。
网上有人说,这个位置改成诸如def date = new Date().format("123")这个形式可以避免生成太多的包,看起来不乱,但是这样的话,由于无法通过命名区分每次的包,所以会出现差异包无法合并到现有app中的问题。
表现出来的样子是,应用被强制关闭了,但是再次打开的时候还是之前的样子。

另外,修改包名在

tinkerOldApkPath = "${bakPath}/app-debug-0424-15-02-56.apk"
OLD_APK=D\:\\Java\\other\\TinkerTest\\app\\build\\bakApk\\app-debug-0424-15-02-56.apk

这两个位置都可以,我建议用OLD_APK的方式,好处刚才也说过了,不乱,并且不会误删。
但是直接在tinkerOldApkPath更新也是可以的,但是这样的话记得把gradle.properties文件中OLD_APK这一行删掉,其它地方不用动。因为代码里会有一个判断语句。

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

3,更新全量包

通过热修复更改过应用后,如果通过正常途径安装新的版本,页面是不会生效的,还是保持热修复之后的样子。
更新全量包的时候,需要更新gradle.properties文件中的变量,TINKER_ID=1.0
这个地方可以使TINKER_ID跟App版本号保持一致,以免忘记。


个人理解,难免有错误纰漏,欢迎指正。转载请注明出处。

你可能感兴趣的:(【总结】Tinker热修复接入)