最初写过Android 热修复入门-Demo实例
这是个理解热修复的很好的例子。
现在想介绍一下 腾讯热修复 Tinker 的实例,也相对简单,并未涉及原理介绍.
1. 下载代码
https://github.com/Tencent/tinker/tree/master
项目结构如上图所示, 有Tinker 的源码 和 示例代码
2. 使用AndroidStudio 打开实例项目
实例项目是: tinker-sample-android 根目录下的 build.gradle
3. 编译apk
Build - build apk
会提示 build error:
Execution failed for task ‘:app:tinkerProcessD‘ . tinkerId is not set!!!
解决办法:
在根目录的 gradle.properties 配置中 , 设置 TINKER_ID 参数
TINKER_ID=1.0
TINKER_ENABLE=true
完整如下:
重新编译则可以成功, 安装apk
参考:https://blog.csdn.net/shulianghan/article/details/116050746
4. 加载补丁包
打开应用, 点击Load patch ,然后点击 show info ,并没有起效。
日志提示:
2022-10-30 09:33:29.822 9703-9703/tinker.sample.android V/Tinker.SamplePatchListener: receive a patch file: /storage/emulated/0/patch_signed_7zip.apk, file size:0
2022-10-30 09:33:29.824 9703-9703/tinker.sample.android I/Tinker.DefaultLoadReporter: patch loadReporter onLoadPatchListenerReceiveFail: patch receive fail: /storage/emulated/0/patch_signed_7zip.apk, code: -2
明显,我们并没有生成 patch 文件
5. 生成补丁包(Patch 文件)
Android Studio -> View ->Tool Windows -> Gradle
找到 Tasks -> tinkerPatchDebug -> 双击即可运行生成操作
这时报错:
tinker-sample-android\app\build\bakApk/app-debug-0424-15-02-56.apk is not exist
原因是旧的apk 信息不对。
解决办法:
(1) 打开文件夹 :tinker-sample-android\app\build\bakApk
里面有几个文件,前缀都是 app-debug-1030-09-16-49
把这个值替换掉 app/build.gradle 下的(共4处):
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-1030-09-16-49.apk"
//proguard mapping file to build patch apk
tinkerApplyMappingPath = "${bakPath}/app-debug-1030-09-16-49.txt"
//resource R.txt to build patch apk, must input if there is resource changed
tinkerApplyResourcePath = "${bakPath}/app-debug-1030-09-16-49.txt"
//only use for build all flavor, if not, just ignore this field
tinkerBuildFlavorDirectory = "${bakPath}/app-debug-1030-09-16-49"
}
然后重新双击 tinkerPatchDebug
则在路径 tinker-sample-android\app\build\outputs\apk\tinkerPatch\debug
生成 app-debug-patch_signed_7zip.apk
6. 拷贝补丁包到手机根目录下
先将上面生成的文件 app-debug-patch_signed_7zip.apk 重命名为 patch_signed_7zip.apk
(因为代码里用到的是 patch_signed_7zip.apk)
即确保存在 storage/emulated/0/patch_signed_7zip.apk
7.重新build apk
Build ->Build apk
8. 再次加载补丁包
进入App -> load patch -> show info
(如果不起效,请尝试先 Kill self 然后再 Load patch -> show info)
成功则会显示 : patch is loaded ...