Android Tinker v1.9.1热补丁接入教程实战以及项目注意点

*本篇文章已授权微信公众号 guolin_blog (郭霖)独家发布


前言:

公司项目开发中可能会经常遇到需求变更,或者刚发布到线上,第二天结果就出现了严重性的bug,导致APP crash,内心是**的,怎么之前没测出来??我不管,测试的锅~ ,测试:开发的锅,于是展开了一场锅王争霸赛~

开个玩笑~

经过debug之后,发现原来是这里出了问题~ 产品经理走过来问,你解释道,这个只能重新发包......

Android Tinker v1.9.1热补丁接入教程实战以及项目注意点_第1张图片

em...不慌,上面的这种情况只要用Tinker都能迎刃而解~


Tinker是什么?

Tinker是微信官方的Android热补丁解决方案,它支持动态下发代码、So库以及资源,让应用能够在不需要重新安装的情况下实现更新。当然,你也可以使用Tinker来更新你的插件。

Android Tinker v1.9.1热补丁接入教程实战以及项目注意点_第2张图片

如何接入?

官方建议我们采用gradle的形式接入,好处是在gradle插件tinker-patch-gradle-plugin中官方帮我们完成proguard、multiDex以及Manifest处理等工作。

添加gradle依赖

为了Tinker版本的可维护性,建议把版本号抽离到项目里的gradle.properties文件中

TINKER_VERSION=1.9.1

在项目的build.gradle中,添加tinker-patch-gradle-plugin的依赖

buildscript {
    dependencies {
        classpath "com.tencent.tinker:tinker-patch-gradle-plugin:${TINKER_VERSION}"
    }
}

然后在app的gradle文件app/build.gradle,我们需要添加tinker的库依赖以及apply tinker的gradle插件.

//apply tinker插件
apply plugin: 'com.tencent.tinker.patch'

dependencies {
    //可选,用于生成application类
    provided("com.tencent.tinker:tinker-android-anno:${TINKER_VERSION}")
    //tinker的核心库
    compile("com.tencent.tinker:tinker-android-lib:${TINKER_VERSION}")
}

然后sync一下...

你以为这样就完事了?


Android Tinker v1.9.1热补丁接入教程实战以及项目注意点_第3张图片

真正到使用上,还要配置一些Tinker的相关参数

完整的 app/build.gradle 如下

android{

    <---省略了一些你自己的项目的配置--->

    signingConfigs {
        debug {
            try {
                storeFile file("keys/***.jks")
                keyAlias ***
                keyPassword ***
                storePassword ***
            } catch (ex) {
                throw new InvalidUserDataException(ex.toString())
            }
        }
        release {
            try {
                storeFile file("keys/***.jks")
                keyAlias ***
                keyPassword ***
                storePassword ***
            } catch (ex) {
                throw new InvalidUserDataException(ex.toString())
            }
        }
    }

    //recommend
    dexOptions {
        jumboMode = true
    }  
}

dependencies {
    //可选,用于生成application类
    provided("com.tencent.tinker:tinker-android-anno:${TINKER_VERSION}")
    //tinker的核心库
    compile("com.tencent.tinker:tinker-android-lib:${TINKER_VERSION}")
}

def gitSha() {
    try {
        String gitRev = 'git rev-parse --short HEAD'.execute(null, project.rootDir).text.trim()
        if (gitRev == null) {
            throw new GradleException("can't get git rev, you should add git to system path or just input test value, such as 'testTinkerId'")
        }
        return gitRev
    } catch (Exception e) {
        throw new GradleException("can't get git rev, you should add git to system path or just input test value, such as 'testTinkerId'")
    }
}

def bakPath = file("${buildDir}/bakApk/")

/**
 * you can use assembleRelease to build you base apk
 * use tinkerPatchRelease -POLD_APK=  -PAPPLY_MAPPING=  -PAPPLY_RESOURCE= to build patch
 * add apk from the build/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-debug-0912-17-33-26.apk"
    //resource R.txt to build patch apk, must input if there is resource changed
    tinkerApplyResourcePath = "${bakPath}/app-debug-0912-17-33-26-R.txt"
}


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

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") ? Boolean.parseBoolean(TINKER_ENABLE) : ext.tinkerEnabled
}

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'
             * 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 = true
        }

        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
        }

        /**
         * 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
                        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")
                        }
                    }
                }
            }
        }
    }
}

关于相关参数的中文解释,这里可以查阅到 Tinker gradle参数详解

什么??你还觉得多?拜托,我已经从官方demo里面剔除到一些不常用的了。

这里我们需要搞清楚一个概念
基准apk包:原apk包称为基准apk包,tinkerPatch直接使用基准apk包与新编译出来的apk包做差异,得到最终的补丁包。

通俗一点讲就是,每次你发布新版本的那个安装包就是基准包,你当前这个版本如果要生成补丁的话,Tinker是用新编译出来的apk包和你的基准包做对比,来产生补丁包,所以每次发布新版本的时候,你都要保存好你自己的安装包。

若配置无误,sync成功后,每次编译运行,Tinker都会在build/bakApk/目录下帮我们生成安装包R.txt,其实这个就相当于你的基准包,以及基准包对应的R.txt

Android Tinker v1.9.1热补丁接入教程实战以及项目注意点_第4张图片

所以我们回顾下我们上面的gradle配置,可以看到一处是我们需要手动管理的。

/**
 * you can use assembleRelease to build you base apk
 * use tinkerPatchRelease -POLD_APK=  -PAPPLY_MAPPING=  -PAPPLY_RESOURCE= to build patch
 * add apk from the build/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-debug-0912-17-33-26.apk"
    //resource R.txt to build patch apk, must input if there is resource changed
    tinkerApplyResourcePath = "${bakPath}/app-debug-0912-17-33-26-R.txt"
}

这个tinkerOldApkPath 以及 tinkerApplyResourcePath 其实就是我们每次要生成某个版本的补丁包的时候,需要手动填入的基准包的路径以及基准包的R.txt,这样讲应该好理解吧。。。

Android Tinker v1.9.1热补丁接入教程实战以及项目注意点_第5张图片


自定义Application类

好,到了这一步,我们的项目可以跑起来了,但是程序启动时会加载默认的Application类,这导致我们补丁包是无法对它做修改了。如何规避?在这里我们并没有使用类似InstantRun hook Application的方式,而是通过代码框架的方式来避免,这也是为了尽量少的去反射,提升框架的兼容性。

这里我们要实现的是完全将原来的Application类隔离起来,即其他任何类都不能再引用我们自己的Application。我们需要做的其实是以下几个工作:

  1. 将我们自己Application类以及它的继承类的所有代码拷贝到自己的ApplicationLike继承类中,例如SampleApplicationLike。你也可以直接将自己的Application改为继承ApplicationLike;
  2. Application的attachBaseContext方法实现要单独移动到onBaseContextAttached中;
  3. 对ApplicationLike中,引用application的地方改成getApplication();
  4. 对其他引用Application或者它的静态对象与方法的地方,改成引用ApplicationLike的静态对象与方法;

更详细的事例,大家可以参考下面的一些例子以及SampleApplicationLike的做法。

如果你不愿意改造自己的应用,可以尝试TinkerPatch的一键傻瓜式接入,具体的可参考文档TinkerPatch 平台介绍。

以上是Tinker官方的术语,PS:我当然愿意改造了
Android Tinker v1.9.1热补丁接入教程实战以及项目注意点_第6张图片

这里要详细讲下,不然有人可能会搞混淆,做法如下:

  1. 新建一个class A extends DefaultApplicationLike;
  2. 把你原Application里attachBaseContext的方法移动到新的A class里的onBaseContextAttached 中
  3. 在你的A class中,引用application的地方改成getApplication()
  4. 外部引用Application它的静态对象与方法的地方,改成引用ApplicationLike的静态对象与方法;
  5. 删除你自己的Application,然后再A class里用Tinker的注解生成自己的Application;
  6. AndroidManifest.xml里面声明Applicaiton路径千万不要填错了,不是A classs!!! 这里是 注解生成Application的路径,第一次报红没关系,编译过后就好了。
import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.multidex.MultiDex;

import com.tencent.tinker.anno.DefaultLifeCycle;
import com.tencent.tinker.lib.tinker.Tinker;
import com.tencent.tinker.lib.tinker.TinkerInstaller;
import com.tencent.tinker.loader.app.DefaultApplicationLike;
import com.tencent.tinker.loader.shareutil.ShareConstants;


/**
 * because you can not use any other class in your application, we need to
 * move your implement of Application to {@link com.tencent.tinker.loader.app.ApplicationLifeCycle}
 * As Application, all its direct reference class should be in the main dex.
 * 

* We use tinker-android-anno to make sure all your classes can be patched. *

* application: if it is start with '.', we will add SampleApplicationLifeCycle's package name *

* flags: * TINKER_ENABLE_ALL: support dex, lib and resource * TINKER_DEX_MASK: just support dex * TINKER_NATIVE_LIBRARY_MASK: just support lib * TINKER_RESOURCE_MASK: just support resource *

* loaderClass: define the tinker loader class, we can just use the default TinkerLoader *

* loadVerifyFlag: whether check files' md5 on the load time, defualt it is false. */ @SuppressWarnings("unused") @DefaultLifeCycle( application = ".MyApplication", //application类名 loaderClass = "com.tencent.tinker.loader.TinkerLoader", //loaderClassName, 我们这里使用默认即可! flags = ShareConstants.TINKER_ENABLE_ALL, loadVerifyFlag = false) public class MyApplicationLike extends DefaultApplicationLike { public static Application application; public MyApplicationLike(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! MultiDex.install(base); MyApplicationLike.application = getApplication(); TinkerInstaller.install(this); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public void registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks callback) { getApplication().registerActivityLifecycleCallbacks(callback); } }

到此为止,Tinker初步的接入已真正的完成,你已经可以愉快的使用Tinker来实现补丁功能了。


使用示例

先看下Tinker安装补丁的语法

TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(), yourFilePath);

注意:因为补丁是需要从服务器上下载到本地,所以这里涉及到SD文件的读取,所以请自行处理APP权限的事情。

假设我们现在走一个正常的开发流程,这个是我的APP,长这样。


Android Tinker v1.9.1热补丁接入教程实战以及项目注意点_第7张图片

上面我们提到过,每次编译运行,Tinker都会帮我们生成基准包和基准包对应的R.txt;所以看一下我们build目录


Android Tinker v1.9.1热补丁接入教程实战以及项目注意点_第8张图片
image.png

这个apk就是我当前手机安装的apk,也就是基准包。

我现在演示如何通过打补丁的形式;

新增文件中....修改代码中.... 这里我新增了一个Activity,然后把上图Button click事件改成跳转到新的页面;

如何生成补丁?

找到我们的gradle配置,把我们上面的基准包及基准包R.txt填写进去。

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-debug-0913-15-49-36.apk"
    //resource R.txt to build patch apk, must input if there is resource changed
    tinkerApplyResourcePath = "${bakPath}/app-debug-0913-15-49-36-R.txt"
}

然后sync一下后,点击Gradle窗口


Android Tinker v1.9.1热补丁接入教程实战以及项目注意点_第9张图片
image.png

我这里使用测试环境打包,正式的话就选择Release,然后Tinker就会读取你在app/build.gradle中signingConfigs中配置key信息。

等待片刻,查看Run窗口log


wow~ successful~
Android Tinker v1.9.1热补丁接入教程实战以及项目注意点_第10张图片

补丁文件在该目录


Android Tinker v1.9.1热补丁接入教程实战以及项目注意点_第11张图片

在tinkerPatch输出目录build/outputs/tinkerPatch中,我们关心的文件有:
patch_unsigned.apk 没有签名的补丁包
patch_signed.apk 签名后的补丁包
patch_signed_7zip.apk 签名后并使用7zip压缩的补丁包,也是我们通常使用的补丁包。但正式发布的时候,最好不要以.apk结尾,防止被运营商挟持。

输出文件更多解析请参阅:
输出文件详解

这时候把patch_signed_7zip.apk 复制到内存卡,模拟用户在服务器上下载了补丁。
开始安装补丁~


Android Tinker v1.9.1热补丁接入教程实战以及项目注意点_第12张图片
点击B menu进行安装

经过一段时间等待,查看log


现在重启APP,见证奇迹~


至此整个流程都介绍的查不多了,更多资料请查阅wiki
Tinker Wiki

关于合成结果回调请查阅:
自定义AbstractResultService类


最后


Android Tinker v1.9.1热补丁接入教程实战以及项目注意点_第13张图片

你可能感兴趣的:(Android Tinker v1.9.1热补丁接入教程实战以及项目注意点)