随着技术的发展,我们来到了热修复时代,网上一大堆关于热修复的文章和框架,相信能来到这里,你也知道什么叫热修复吧,让我用通俗的语言给大家定义一个概念:
热修复就是在无需重新安装应用的情况下,修改目前存在的bug,或者新增功能
这样讲是不是蛮好理解的。
然后我们再众多热修复框架中,选择Tinker作为我们实现热修复的手段。那就来吧!
前言
其实怎么接入tinker,官方已经给出了方法,但是我们在接入的时候,难免会遇到不少问题(官方文档不是非常非常详细背锅)。其实官方文档写的还是蛮详细的,只是我们在照着文档操作的时候,还是有那么一点不顺畅,中间遇到一些小问题,所以我希望大家在观看我这篇文章后,能够丝滑接入Tinker,并得到成就感。那,我们就开始吧!
依赖接入
假设你已经创建好一个新项目了(我用的Android studio 3.1.2),首先我们先给这个应用加上依赖吧,需要加依赖的地方有2个,我们一个一个来:
- 在项目根build.gradle添加以下依赖:
classpath ('com.tencent.tinker:tinker-patch-gradle-plugin:1.9.1')
- 在应用目录添加以下依赖
// 可选,用于生成application类
compileOnly('com.tencent.tinker:tinker-android-anno:1.9.1')
// tinker的核心库
implementation('com.tencent.tinker:tinker-android-lib:1.9.1')
// Google提供的分包小助手
implementation "com.android.support:multidex:1.0.3"
Gradle配置
注:以下配置,均在app的gradle文件中做配置
在项目的build.gradle中配置,在做配置前,我们先创建两个签名文件,一个作为正式版的签名,另一个作为debug版的签名吧,然后放到项目中,这是为了使以后直接就生成签名后的apk文件,免得生成apk以后还要自己去签一次名。
这里我偷个懒,直接用tinker-sample-android中的签名吧,签名放这里。
我们先来配置下签名,在android{}
中做以下配置:
android{
...
// 这里做签名的配置
signingConfigs {
release {
try {
storeFile file("./keystore/release.keystore")
storePassword "testres"
keyAlias "testres"
keyPassword "testres"
} catch (ex) {
throw new InvalidUserDataException(ex.toString())
}
}
debug {
storeFile file("./keystore/debug.keystore")
}
}
...
}
然后我们再指定下构建的种类:
android {
...
buildTypes {
release {
minifyEnabled true
signingConfig signingConfigs.release
proguardFiles getDefaultProguardFile('proguard-android.txt'), project.file('proguard-rules.pro')
}
debug {
debuggable true
minifyEnabled false
signingConfig signingConfigs.debug
}
}
...
}
还记得我们添加了Google提供的分包小助手吗,我们需要开启这个分包的功能:
android {
...
defaultConfig {
...
multiDexEnabled true // 开启dex分包
...
}
}
好的,以上就把android{}
中的东西配置的差不多了,接下来我们需要配置点其他东西,具体配置可以参照官方的build.gradle,不过官方配置的东西太多了,但我没打算配置这么多东西,所以来看看我们的版本(其实也挺多),直接上码?
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-1018-17-32-47.apk"
//proguard mapping file to build patch apk
tinkerApplyMappingPath = "${bakPath}/app-debug-1018-17-32-47-mapping.txt"
//resource R.txt to build patch apk, must input if there is resource changed
tinkerApplyResourcePath = "${bakPath}/app-debug-1018-17-32-47-R.txt"
//only use for build all flavor, if not, just ignore this field
tinkerBuildFlavorDirectory = "${bakPath}/app-1018-17-32-47"
}
def getApplyMappingPath() {
return hasProperty("APPLY_MAPPING") ? APPLY_MAPPING : ext.tinkerApplyMappingPath
}
def getApplyResourceMappingPath() {
return hasProperty("APPLY_RESOURCE") ? APPLY_RESOURCE : ext.tinkerApplyResourcePath
}
def buildWithTinker() {
return hasProperty("TINKER_ENABLE") ? Boolean.parseBoolean(TINKER_ENABLE) : ext.tinkerEnabled
}
def getTinkerBuildFlavorDirectory() {
return ext.tinkerBuildFlavorDirectory
}
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 = "${bakPath}/app-debug-0704-16-30-41.apk"
/**
* 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 = "tinkerdemo"
/**
* if keepDexApply is true, class in which dex refer to the old apk.
* open this can reduce the dex diff file size.
*/
keepDexApply = false
// 如果你用到了各种加固,你需要把这里设置为true
isProtectedApp = 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
}
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"
}
}
List<String> 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")
}
}
}
}
}
}
project.afterEvaluate {
//sample use for build all flavor for one time
if (hasFlavors) {
task(tinkerPatchAllFlavorRelease) {
group = 'tinker'
def originOldPath = getTinkerBuildFlavorDirectory()
for (String flavor : flavors) {
def tinkerTask = tasks.getByName("tinkerPatch${flavor.capitalize()}Release")
dependsOn tinkerTask
def preAssembleTask = tasks.getByName("process${flavor.capitalize()}ReleaseManifest")
preAssembleTask.doFirst {
String flavorName = preAssembleTask.name.substring(7, 8).toLowerCase() + preAssembleTask.name.substring(8, preAssembleTask.name.length() - 15)
project.tinkerPatch.oldApk = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-release.apk"
project.tinkerPatch.buildConfig.applyMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-release-mapping.txt"
project.tinkerPatch.buildConfig.applyResourceMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-release-R.txt"
}
}
}
task(tinkerPatchAllFlavorDebug) {
group = 'tinker'
def originOldPath = getTinkerBuildFlavorDirectory()
for (String flavor : flavors) {
def tinkerTask = tasks.getByName("tinkerPatch${flavor.capitalize()}Debug")
dependsOn tinkerTask
def preAssembleTask = tasks.getByName("process${flavor.capitalize()}DebugManifest")
preAssembleTask.doFirst {
String flavorName = preAssembleTask.name.substring(7, 8).toLowerCase() + preAssembleTask.name.substring(8, preAssembleTask.name.length() - 13)
project.tinkerPatch.oldApk = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-debug.apk"
project.tinkerPatch.buildConfig.applyMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-debug-mapping.txt"
project.tinkerPatch.buildConfig.applyResourceMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-debug-R.txt"
}
}
}
}
}
}
还是挺多的对不?我知道你要CV大法了。
简单配置
按照以上步骤,我相信你应该已经配置完毕了,接下来我们就要开始使用了,如何在代码中使用这些东西呢。
在Tinker里面,有一个叫着ApplicatioLike的东西,这个东西,看着名字挺像Application的让人怀疑它是Application的子类,其实不是的,不过这个类你完全可以把它当作一个Application来使用,好吧,我们来使用一下吧。
首先我们创建一个类MyApplicationLike
来继承Application
,OK,里面要怎么写呢?
@DefaultLifeCycle(
// 将 要自动生成的application的类,指定生成位置和类名
application = "com.qxf.tinkerdemo.MyApplication",
flags = ShareConstants.TINKER_ENABLE_ALL,
//loaderClassName, 我们这里使用默认即可!
loaderClass = "com.tencent.tinker.loader.TinkerLoader",
loadVerifyFlag = false)
public class MyApplicationLike extends ApplicationLike {
public MyApplicationLike(
Application application,
int tinkerFlags,
boolean tinkerLoadVerifyFlag,
long applicationStartElapsedTime,
long applicationStartMillisTime,
Intent tinkerResultIntent) {
super(
application,
tinkerFlags,
tinkerLoadVerifyFlag,
applicationStartElapsedTime,
applicationStartMillisTime,
tinkerResultIntent);
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks callback) {
getApplication().registerActivityLifecycleCallbacks(callback);
}
}
(上面的代码,别光顾着复制到自己的项目中就完了,记得看一下,有注释的= =)
然后我们build以下项目,我们会发现项目中的这里,自动生成了一个类:
既然现在有application了,那我们就在AndroidManifest.xml
中做一些配置吧。
首先加上两个权限,内存读写权限,至于Android版本大于6.0的手机,记得要做一下动态授权,以免到时候找不到补丁包:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
然后加上自动生成的application:
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--顺便加上这个服务,tinker自带的-->
<service android:name="com.tencent.tinker.lib.service.DefaultTinkerResultService" />
</application>
既然application已经配置完毕了,我们再回头来看看MyApplicationLike
这个类,这个类里面要写一些东西,来表示我们不止会配置,还会用。
我们要重写onBaseContextAttached
方法,那就来吧:
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void onBaseContextAttached(Context base) {
super.onBaseContextAttached(base);
// 分包需要的东西
MultiDex.install(base);
// LoadReporter类定义了Tinker在加载补丁时的一些回调
LoadReporter loadReporter = new DefaultLoadReporter(getApplication());
// PatchReporter类定义了Tinker在修复或者升级补丁时的一些回调
PatchReporter patchReporter = new DefaultPatchReporter(getApplication());
// PatchListener类是用来过滤Tinker收到的补丁包的修复、升级请求,也就是决定我们是不是真的要唤起:patch进程去尝试补丁合成。
PatchListener patchListener = new DefaultPatchListener(getApplication());
// UpgradePatch类是用来升级当前补丁包的处理类,一般来说你也不需要复写它。
AbstractPatch upgradePatchProcessor = new UpgradePatch();
TinkerInstaller.install(this,
loadReporter, patchReporter, patchListener,
DefaultTinkerResultService.class, upgradePatchProcessor);
}
老实说,其实这里的也算配置= =
不过到这里到时候,我们的Tinker,简单的配置,基本就都完成了。
实践
现在我们要开始正式使用tinker了。
tinker的使用过程(概念):
1. 运行含有bug的app
2. 加载补丁
3. 重启应用
4. bug消失
我们无法判断应用是否有bug,因为上线的时候肯定是感觉各个地方都没有问题才上线的吧(汗!)
我们这样来测试吧,MainActivity
做两个按钮,一个加载补丁的按钮,一个测试按钮。嗯,说干就干!
界面搭建:
界面就这么简单了
点击事件的逻辑如下:
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.load:
// 加载补丁
TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(),
Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed_7zip.apk");
break;
case R.id.test:
show.setText("测试结果:"+"bug");
break;
}
}
接下来我们将这个打包成APK,在这里打包
打包完毕后,在这里会生成一个apk
将这个apk安装到手机上,然后点击一下测试,好吧,你们已经猜到答案了:
然后我们来修复以下这个伪bug,就这样修复吧
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.load:
// 加载补丁
TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(),
Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed_7zip.apk");
break;
case R.id.test:
show.setText("测试结果:"+"bug已被修复");
break;
}
}
我们把生成的刚刚生成的APK的名字,复制到app下的build.gradle中oldApk这里,像这样
然后我们利用tinker的打包工具tinkerPatchDebug生成补丁
生成的补丁将会来到这里
接下来重点来了,我们要将这个文件放到手机的指定位置/storage/emulated/0
(毕竟是个demo,就不把补丁放到服务器上,然后从服务器下载到手机上再加载补丁了),所以我就直接通过adb命令直接把文件push到手机上了。
push命令这里大概说一下:
adb push 电脑上的文件的路径 手机路径
这里顺便说一个你们可能已经知道了的快捷键,选中studio中的文件,crtl+shift+c 可以直接复制文件的绝对路径
好了,现在我们重新打开应用看看怎么样了,重新打开应用,点击加载补丁,加载完补丁后,点击测试,还是有bug,不过重启应用后,再次点击,我们将会看到,bug已经被修复了
tinker的简单使用差不多就是这样,各种配置完毕后,得到补丁,加载补丁,重启应用,bug消失。
常见问题
在使用tinker的时候,可能会遇到一些小问题,我这里大概说几个:
找不到补丁文件
多半都是你没有加读写权限,可能你加了,但是由于你手机是Android6.0以上,所以需要动态获取权限tinkerId is not set!!!
如果按照我的方式来,应该不会出现这些问题,出现这个问题的主要原因多半都是按照官方说明接入的,由于官方获取tinkerId是通过得到git提交的提交码得到的,所以只需要把代码通过git提交一次就可以得到tinkerId了,不过我不喜欢这样做,因为像我这种写一行代码都可能会提交的人来说,tinkerId会一直变动。Annotation processors must be explicitly declared now.
有可能在使用Tinker的时候,会报这个错,解决方案也很简单:
javaCompileOptions { annotationProcessorOptions { includeCompileClasspath = true } }
将这句代码,加入android{}下的defaultConfig{}里面即可
加固
这里多提一句,isProtectedApp,关于这个属性,如果要使用加固的功能,需要把这个值设置为true,搬一下官方的话就是:
tinker 1.7.8 可以通过 isProtectedApp 开启加固支持,这种模式仅仅可以使用在加固应用中。
支持加固的厂商有:
腾讯云·乐固
爱加密
梆梆加固
360加固(需要5月8号后的加固版本)
其他 请自行测试,只要满足下面规则的都可以支持
这里是否支持加固,需要加固厂商明确以下两点:
1.不能提前导入类;
2.在art平台若要编译oat文件,需要将内联取消。
其他常见问题或许你可以在官方常见问题这里找到答案。
最后
Tinker提供的东西不止我这里写的这么简单,大家可以参考Tinker自定义扩展,其实Tinker还是很灵活的,推荐大概看下自定义扩展里面的内容,然后在把官方的例子tinker-sample-android下载下来好好看看官方是这么实现的,相信你能够了解到更多的东西。