Gradle实战2:微信Tinker项目中的tinker-patch-gradle-plugin模块解析

引言

上一篇,我们学习了《微信Tinker项目中的maven-publish封装》,了解到了在一个成熟项目中,maven相关gradle的通用封装,进而巩固前面学习的gradle相关理论知识

接下来,我们将对Tinker项目中的tinker-patch-gradle-plugin模块进行解析,进一步感受Gradle在亿级应用中散发的魅力

PS1:本章主要是跟踪《tinker-patch-gradle-plugin模块》实现,来巩固gradle相关知识,具体热修相关安卓知识的话不会展开

PS2:由于tinker的官方工程比较大,对于巩固gradle知识干扰比较大,所以本章的代码工程是阉割了官方的代码展开,更加聚焦,同时实现博客和源码配套的模式

简介

tinker-patch-gradle-plugin模块,是开发者使用Thinker入口;

如果我们app集成thinker,其实就是对这个模块的使用,因为thinker的实现

都以插件的方式被封装到了这个模块,具体官方代码位置戳这里>>>

上面说到,我们会对官方工程进行裁剪,裁剪后对应的模块位置戳这里>>>

解析过程

应用模块

1.png
此图为我们的app模块引入thinker的步骤

1)模块所在位置,其实就是我们app模块的gradle文件

2)插件引入,通过classpath关键字引入封装好的thinker插件,其中插件的maven发布我们发布到了本地,所以用的时候我们maven指向了本地的 ‘../repo’

3)插件的使用,通过apply引入,然后tinkerPatch,buildConfig都是插件的自定义拓展,具体实现在下面步骤讲解

模块之工程定义

2.png

1)插件实现工程目录,可以看出这是一个gradle插件的标准目录,具体诠释见往期教程

2)插件实现工程gradle文件,这里除了有自定义插件的依赖外,还用到了上一章讲解的maven-publish封装

模块之自定义拓展

上面有提到tinkerPatch,buildConfig关键字为自定义拓展,这两个关键字只是thinker

中的拓展之一,我们来看下thinker的自定义拓展全貌:

 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.
             *
             * <b>Notice that currently this feature is incubating and only support NON-EXPORTED Activity</b>
             */
            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"
        }
    }
复制代码

精简后大致结构如下:

 tinkerPatch {
        oldApk = getOldApkPath()
        buildConfig {
            supportHotplugComponent = false
        }
        dex {
            pattern = ["classes*.dex",
                       "assets/secondary-dex-?.jar"]
        }
        lib {
            pattern = ["lib/*/*.so"]
        }
        res {
            largeModSize = 100
        }
        packageConfig {
            configField("patchVersion", "1.0")
        }
        sevenZip {
            zipArtifact = "com.tencent.mm:SevenZip:1.1.10"
        }
 }
复制代码

这里具体的配置是什么意思,先不用关注,因为配置的意思涉及到thinker本身业务和一些安卓热修相关知识点,我们主要关注下如果我们要实现这样的结构拓展,应该怎么做?下面我们来看看thinker是怎么做的:

3.png

1)插件入口,gradle插件的代码类入口

2)和 3),拓展调用和定义,在定义中可以看到通过‘project.extensions.create’
来创建自定义拓展,层级嵌套拓展通过追加方式,如:先自定义tinkerPatch,然后在tinkerPatch中嵌套buildConfig

其中,细心的朋友会看到,为什么有些create是2个参数,有些是3个参数

4.png

根据官方定义可以看出,前面两个是定义拓展的key和value,然后后面的可变参数是
要传给value拓展的参数,举个例子:

project.tinkerPatch.extensions.create('buildConfig', TinkerBuildConfigExtension, project)
复制代码

key为‘buildConfig’,value为‘TinkerBuildConfigExtension’

然后project则是传递参数给到了‘TinkerBuildConfigExtension’,具体见TinkerBuildConfigExtension的定义如下:

6.png

其他拓展以此类推,这里不一一展开

模块之配置android属性

7.png

1)preDexLibraries 设置为false

默认情况下,preDexLibraries是为true的,作用主要是用来确认是否对Lib做preDexing操作,操作了的话带来的好处提高增量构建的速度;

这里设置为false,猜测是thinker涉及了多dex,为避免和库工程冲突

另外preDexLibraries是dexOptions属性之一,dexoptions是一个gradle对象,这个对象用来设置从java代码向.dex文件转化的过程中的一些配置选项;

更多dexOptions属性可以戳这里>>>

2)jumboMode 设置为true

jumboMode设置为true,意识是忽略方法数限制的检查

这样做的缺点是apk无法再低版本的设备上面安装,会出现错误:INSTALL_FAILED_DEXOPT

具体细节戳这里>>>

3)关闭 ENABLE_DEX_ARCHIVE

void disableArchiveDex(Project project) {
        println 'disableArchiveDex -->'
        try {
            def booleanOptClazz = Class.forName('com.android.build.gradle.options.BooleanOption')
            def enableDexArchiveField = booleanOptClazz.getDeclaredField('ENABLE_DEX_ARCHIVE')
            enableDexArchiveField.setAccessible(true)
            def enableDexArchiveEnumObj = enableDexArchiveField.get(null)
            def defValField = enableDexArchiveEnumObj.getClass().getDeclaredField('defaultValue')
            defValField.setAccessible(true)
            defValField.set(enableDexArchiveEnumObj, false)
        } catch (Throwable thr) {
            // To some extends, class not found means we are in lower version of android gradle
            // plugin, so just ignore that exception.
            if (!(thr instanceof ClassNotFoundException)) {
                project.logger.error("reflectDexArchiveFlag error: ${thr.getMessage()}.")
            }
        }
    } 
复制代码

ENABLE_DEX_ARCHIVE 这个功能主要是减少dex的大小

这里关闭主要避免破坏multidex的maindex规则,进而实现多dex的场景

4)keepRuntimeAnnotatedClasses 设置为 false

keepRuntimeAnnotatedClasses 主要作用是带有运行时注解的类,保留在主dex中

thinker关闭,主要降低主dex大小,兼容5.0以下的情况

模块之aapt2和资源固定相关

1.png
2.png

该部分功能实现:使用导出的符号表进行资源id的固定

为什么要进行资源ID的固定?具体戳这里>>,背景细节不在这展开

其中,这里实现逻辑为:

1)判断当前《Android Gradle Plugin》是否启动aapt2,如果没有启动跳过,如果启动了则进行aapt2的资源固定适配

2)aapt2的资源固定适配操作,通过指定稳定的资源id映射文件,同时结合“–stable-ids”命令进行固定

源码

戳这里>>>

小结

到这里gradle的学习接下来就要告一断落了,前面主要是学习了系列基础理论,然后结合了两篇实战进行巩固,剩下的就要靠自己项目中不断的使用,才能进入到下一步高级的境界;

结尾

哈哈,该篇就写到这里(一起体系化学习,一起成长)

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享