Android 热修复 - Tinker 实现及踩过的坑

1,237 阅读2分钟

转载请注明出处:juejin.cn/post/684490…

写在开头

Android 热修复 - 各框架原理学习及对比 一文中,介绍了Nuwa、Robust、Andfix 和 Tinker 的实现原理,以及优缺点对比等。下面我们就让 Tinker-Demo跑起来,看看实际效果以及解决集成过程中遇到的问题。

Tinker-Demo 效果

下载 Github 上的开源代码,然后仅需导入 tinker-sample-android 工程即可。

添加依赖

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

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

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

dependencies {
	//可选,用于生成application类 
	provided('com.tencent.tinker:tinker-android-anno:1.9.1')
    //tinker的核心库
    compile('com.tencent.tinker:tinker-android-lib:1.9.1') 
}
...
//apply tinker插件
apply plugin: 'com.tencent.tinker.patch'

准备好后,运行...

tinkerId is not set!!!

看一下app/build.gradle中在哪里设置tinkerId。

tinkerId

def getTinkerIdValue() {
    return hasProperty("TINKER_ID") ? TINKER_ID : gitSha()
}
def gitSha() {
        String gitRev = 'git rev-parse --short HEAD'.execute(null, project.rootDir).text.trim()
        ...

这里是 Tinker 官方的常见问题文档 Tinker常见问题文档

tinkerId is not set 官网回答

这里设置成版本号即可

String gitRev = '1.9.1'

再运行... 点击 SHOW INFO 按钮

这里写图片描述

生成补丁包

MainActivity.java中添加代码

Toast.makeText(this, "hello, Tinker", Toast.LENGTH_SHORT).show();

在app/build.gralde中,将刚才生成的apk包标记为oldApk

if (buildWithTinker()) {
    apply plugin: 'com.tencent.tinker.patch'
    tinkerPatch {
    ...
        oldApk = getOldApkPath()
def getOldApkPath() {
    return hasProperty("OLD_APK") ? OLD_APK : ext.tinkerOldApkPath
}

oldApkPath

包名改成和左边的一样。 在底部Terminal中输入生成补丁包的命令 graldew tinkerPatchDebug ... 报错

com.tencent.tinker.build.util.TinkerPatchException:
Warning: ignoreWarning is false, manifest was changed, while hot plug component support mode is disabled. Such changes will not take effect.

搜了下Issues,有相同的问题。官方技术大佬是怎么回复的,不过具体原因还有待研究...

官方技术大佬的回复

ignoreWarning = true 这里设置为忽略警告,再次 graldew tinkerPatchDebug

成功之后有个patch_signed_7zip.apk

patch_signed_7zip.apk

下载并合成补丁

可以使用命令行将补丁包发送到手机。 adb push ./app/build/outputs/apk/tinkerPatch/debug/patch_signed_7zip.apk /storage/sdcard0/

不过这里运行失败了 `adb server is out of date. killing... CreateProcess failure, error 2

  • failed to start daemon * error:` 试了一大堆方法,无果...

好吧!手动拷贝到手机文件管理根目录下。 再次打开Tinker-Demo 点击LOAD PATCH 按钮 过了2-3s 出现Toast 提示

Toast 提示

返回,再进入... 没反应 这里注意,必须要杀掉进程,再次进来才能成功加载patch包的代码。 手动杀掉,或者点击KILL SELF 按钮

hello, Tinker

完成修复

写在后头

各个框架各有优劣,Tinker 官方在文档中也指出其不足之处:

Tinker经过几次全量上线,也发现了一些热补丁的问题。有以下的一些优化工作尚未完成: 1. 支持四大组件的代理; 2. Crash 启动保护;

道阻且长,目前Tinker 还只能是替换类、资源和so 文件等,如果支持了四大组件的代理,也许所有的非重大版本更新都可以用热修复来实现了。

推荐阅读:Android 热修复 - 各框架原理学习及对比
Amigo学习(一)解决使用中遇到的问题比

记录在此,仅为学习!
感谢您的阅读!欢迎指正!