官方文档:https://github.com/Tencent/tinker 下面我们按照官方文档和这个里面的tinker-sample-android来进行集成Tinker。
注意 说明,官方demo的使用https://github.com/Tencent/tinker/wiki/Tinker-接入指南里面的使用步骤详解
热加载
简单的说 如果Android要加载一个类 就会调用ClassLoader的findClass方法 在dex中查找这个类 找到后加载到内存
而我们要做的就是在findClass的时候让类加载找到的是我们修复过后的类,而不是未修复的类。
至于是如何做到的暂时还没有深究,个人理解大概是通过反射替换了ClassLoader,通过自定义的ClassLoader去加载更新之后的类文件从而完成替换
直接上手
关于热更新介绍和机制,网上很多介绍,这里简单记录一下小白使用Tinker热更新的经历
跑通demo,稍后再说导入
https://github.com/Tencent/tinker
- 将tinker-sample-android 导入
这里要注意的是
需要将app 下的gradle 中 gitRev 字段自己赋值,因为在没有配置git的情况下,无法获取,这个值作为Tinker 的Id,我好像没感觉这个玩意有啥用,应该是唯一的即可,然后这个项目就可以根据编译打包啦(即带有bug需要修复的线上版本) 修改Bug
比如给随便一个按钮点击事件中多打印一个Toast
打差异包
首先在Gradle中配置带有bug的apk路径,以及资源文件txt路径,以便让Tinker新老apk进行比较,生成差异包
在AS自带命令行中输入 gradlew tinkerPatchDebug,如果其中报错
Warning:ignoreWarning is false, but resources.arsc is changed, you should use applyResourceMapping mode to build the new apk, otherwise, it may be crash at some times
com.tencent.tinker.build.util.TinkerPatchException: ignoreWarning is false, but resources.arsc is changed, you should use applyResourceMapping mode to build the new apk, otherwise, it may be crash at some times
FAILURE: Build failed with an exception.
What went wrong:
Could not dispatch a message to the daemon.Try:
Run with –stacktrace option to get the stack trace. Run with –info or –debug option to get more log output.
,可在Gradle中尝试打开警告忽略
4.将生成的Patch包导入代码中的加载路径,默认项目中MainActivity中写死了,在存储卡根目录
TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath() + “/patch_signed_7zip.apk”);
patch默认生成在
5.最后一步,调用
TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed_7zip.apk");
即可,然后将程序关闭,重新打开,就执行的是新的代码啦~
导入到自己的工程
推荐使用Gradle导入
在app下添加
apply plugin: 'com.tencent.tinker.patch'
compile('com.tencent.tinker:tinker-android-anno:1.7.11')
//tinker的核心库
compile('com.tencent.tinker:tinker-android-lib:1.7.11')
compile "com.android.support:multidex:1.0.1"
project.gradle
classpath ('com.tencent.tinker:tinker-patch-gradle-plugin:1.7.11')
附上我的完整gradle文件,注意,一定要配置签名文件
apply plugin: 'com.android.application'
apply plugin: 'com.tencent.tinker.patch'
def gitSha() {
try {
// String gitRev = 'git rev-parse --short HEAD'.execute(null, project.rootDir).text.trim()
String gitRev = "fushuang666"
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 javaVersion = JavaVersion.V