本文章参考官方文档:https://github.com/Tencent/tinker
为什么使用Tinker
当前市面的热补丁方案有很多,其中比较出名的有阿里的AndFix、美团的Robust以及QZone的超级补丁方案。但它们都存在无法解决的问题,这也是正是我们推出Tinker的原因。
| Tinker | QZone | AndFix | Robust | |
|---|---|---|---|---|
| 类替换 | yes | yes | no | no |
| So替换 | yes | no | no | no |
| 资源替换 | yes | yes | no | no |
| 全平台支持 | yes | yes | yes | yes |
| 即时生效 | no | no | yes | yes |
| 性能损耗 | 较小 | 较大 | 较小 | 较小 |
| 补丁包大小 | 较小 | 较大 | 一般 | 一般 |
| 开发透明 | yes | yes | no | no |
| 复杂度 | 较低 | 较低 | 复杂 | 复杂 |
| gradle支持 | yes | no | no | no |
| Rom体积 | 较大 | 较小 | 较小 | 较小 |
| 成功率 | 较高 | 较高 | 一般 | 最高 |
总的来说:
- AndFix作为native解决方案,首先面临的是稳定性与兼容性问题,更重要的是它无法实现类替换,它是需要大量额外的开发成本的;
- Robust兼容性与成功率较高,但是它与AndFix一样,无法新增变量与类只能用做的bugFix方案;
- Qzone方案可以做到发布产品功能,但是它主要问题是插桩带来Dalvik的性能问题,以及为了解决Art下内存地址问题而导致补丁包急速增大的。
特别是在Android N之后,由于混合编译的inline策略修改,对于市面上的各种方案都不太容易解决。而Tinker热补丁方案不仅支持类、So以及资源的替换,它还是2.X-8.X(1.9.0以上支持8.X)的全平台支持。利用Tinker我们不仅可以用做bugfix,甚至可以替代功能的发布。Tinker已运行在微信的数亿Android设备上,那么为什么你不使用Tinker呢?
如何使用Tinker
添加gradle依赖
在项目的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'
使用命令行生产补丁apk文件的步骤,下面给个Demo说明:
https://github.com/zhengwanshi/MyTinker新建一个工程,加上上面的那些配置
在app的build.gradle里面配置
//可选,用于生成application类 provided('com.tencent.tinker:tinker-android-anno:1.9.1') //tinker的核心库 compile('com.tencent.tinker:tinker-android-lib:1.9.1') compile "com.android.support:multidex:1.0.1"
配置签名文件:
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
signingConfigs{
release{
try {
storeFile file("zhengwanshi_signing.jks")
storePassword "xxxxx"
keyAlias "MyAlias"
keyPassword "xxxxx"
}catch(ex){
throw new InvalidUserDataException(ex.toString())
}
}
}
新建TinkerManager类对Tinker的api做封装
public class TinkerManager { private static boolean isInstalled = false; private static ApplicationLike mAppLike; // private static CustomPatchListener mPatchListener; /** * 完成Tinker的初始化 * * @param applicationLike */ public static void installTinker(ApplicationLike applicationLike) { mAppLike = applicationLike; if (isInstalled) { return; } TinkerInstaller.install(mAppLike); isInstalled = true; } //完成Patch文件的加载 public static void loadPatch(String path) { if (Tinker.isTinkerInstalled()) { TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(), path); } } //通过ApplicationLike获取Context private static Context getApplicationContext() { if (mAppLike != null) { return mAppLike.getApplication().getApplicationContext(); } return null; } }
新建CostomTinkerLike对Tinker做初始化操作
@DefaultLifeCycle(application = ".MyTinkerApplication", flags = ShareConstants.TINKER_ENABLE_ALL, loadVerifyFlag = false)//这个注解很重要,编译后自动生成MyTinkerApplication类 public class CustomTinkerLike extends ApplicationLike{ public CustomTinkerLike(Application application, int tinkerFlags, boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime, long applicationStartMillisTime, Intent tinkerResultIntent) { super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent); } @Override public void onBaseContextAttached(Context base) { super.onBaseContextAttached(base); MultiDex.install(base); TinkerManager.installTinker(this); } }
在MainActivity中调用加载
public class MainActivity extends AppCompatActivity { private static final String FILE_END = ".apk"; private String mPatchDir; private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mPatchDir = getExternalCacheDir().getAbsolutePath()+"/tpatch/"; //创建文件夹 File file = new File(mPatchDir); if (file == null ||file.exists()){ file.mkdir(); } } public void loadPatch(View view){ TinkerManager.loadPatch(getPatchName()); } private String getPatchName() { Log.e(TAG, "getPatchName: "+mPatchDir.concat("zhengwanshi").concat(FILE_END)); return mPatchDir.concat("patch_signed").concat(FILE_END); } }
在AndroidManifest.xml文件中
对application选项中
android:name=".tinker.MyTinkerApplication"
只有id相同才能修复
<meta-data android:name="TINKER_ID" android:value="tinker_id_1234"/>
修复工具里面的文件如下
其中修改tinker_config.xml 文件一定要记得

其中修改tinker_config.xml 文件一定要记得,修改第二个loader 的value,值是我们新建的MyTinkerApplication

修改签名文件配置

我写了一个脚本命令:生成命令.bat 内容:
java -jar tinker-patch-cli-1.7.7.jar -old old.apk -new new.apk -config tinker_config.xml -out output
最后生成apk等文件

其中patch_signed.apk 就是我们要的
然后执行push命令发到手机
adb push patch_signed.apk /storage/emulated/0/Android/data/com.example.mytinker/cache/tpatch/patch_signed.apk
使用Gradle生成补丁apk文件:
配置gradle.properties 便于版本控制

接下来就是配置app下的build.gradle文件了
gradle参数详解
我们将原apk包称为基准apk包,tinkerPatch直接使用基准apk包与新编译出来的apk包做差异,得到最终的补丁包。gradle配置的参数详细解释如下:
| 参数 | 默认值 | 描述 |
|---|---|---|
tinkerPatch | 全局信息相关的配置项 | |
| tinkerEnable | true | 是否打开tinker的功能。 |
| oldApk | null | 基准apk包的路径,必须输入,否则会报错。 |
| newApk | null | 选填,用于编译补丁apk路径。如果路径合法,即不再编译新的安装包,使用oldApk与newApk直接编译。 |
| outputFolder null | 选填,设置编译输出路径。默认在build/outputs/tinkerPatch中 | |
| ignoreWarning | false | 如果出现以下的情况,并且ignoreWarning为false,我们将中断编译。因为这些情况可能会导致编译出来的patch包带来风险: 1. minSdkVersion小于14,但是 dexMode的值为"raw";2. 新编译的安装包出现新增的四大组件(Activity, BroadcastReceiver...); 3. 定义在dex.loader用于加载补丁的类不在main dex中; 4. 定义在dex.loader用于加载补丁的类出现修改; 5. resources.arsc改变,但没有使用applyResourceMapping编译。 |
| useSign | true | 在运行过程中,我们需要验证基准apk包与补丁包的签名是否一致,我们是否需要为你签名。 |
buildConfig | 编译相关的配置项 | |
| applyMapping | null | 可选参数;在编译新的apk时候,我们希望通过保持旧apk的proguard混淆方式,从而减少补丁包的大小。这个只是推荐设置,不设置applyMapping也不会影响任何的assemble编译。 |
| applyResourceMapping | null | 可选参数;在编译新的apk时候,我们希望通过旧apk的R.txt文件保持ResId的分配,这样不仅可以减少补丁包的大小,同时也避免由于ResId改变导致remote view异常。 |
| tinkerId | null | 在运行过程中,我们需要验证基准apk包的tinkerId是否等于补丁包的tinkerId。这个是决定补丁包能运行在哪些基准包上面,一般来说我们可以使用git版本号、versionName等等。 |
| keepDexApply | false | 如果我们有多个dex,编译补丁时可能会由于类的移动导致变更增多。若打开keepDexApply模式,补丁包将根据基准包的类分布来编译。 |
| isProtectedApp | false | 是否使用加固模式,仅仅将变更的类合成补丁。注意,这种模式仅仅可以用于加固应用中。 |
| supportHotplugComponent(added 1.9.0) | false | 是否支持新增非export的Activity |
dex | dex相关的配置项 | |
| dexMode | jar | 只能是'raw'或者'jar'。 对于'raw'模式,我们将会保持输入dex的格式。 对于'jar'模式,我们将会把输入dex重新压缩封装到jar。如果你的minSdkVersion小于14,你必须选择‘jar’模式,而且它更省存储空间,但是验证md5时比'raw'模式耗时。默认我们并不会去校验md5,一般情况下选择jar模式即可。 |
| pattern | [] | 需要处理dex路径,支持*、?通配符,必须使用'/'分割。路径是相对安装包的,例如assets/... |
| loader | [] | 这一项非常重要,它定义了哪些类在加载补丁包的时候会用到。这些类是通过Tinker无法修改的类,也是一定要放在main dex的类。 这里需要定义的类有: 1. 你自己定义的Application类; 2. Tinker库中用于加载补丁包的部分类,即com.tencent.tinker.loader.*; 3. 如果你自定义了TinkerLoader,需要将它以及它引用的所有类也加入loader中; 4. 其他一些你不希望被更改的类,例如Sample中的BaseBuildInfo类。这里需要注意的是,这些类的直接引用类也需要加入到loader中。或者你需要将这个类变成非preverify。 5. 使用1.7.6版本之后的gradle版本,参数1、2会自动填写。若使用newApk或者命令行版本编译,1、2依然需要手动填写 |
lib | lib相关的配置项 | |
| pattern | [] | 需要处理lib路径,支持*、?通配符,必须使用'/'分割。与dex.pattern一致, 路径是相对安装包的,例如assets/... |
res | res相关的配置项 | |
| pattern | [] | 需要处理res路径,支持*、?通配符,必须使用'/'分割。与dex.pattern一致, 路径是相对安装包的,例如assets/...,务必注意的是,只有满足pattern的资源才会放到合成后的资源包。 |
| ignoreChange | [] | 支持*、?通配符,必须使用'/'分割。若满足ignoreChange的pattern,在编译时会忽略该文件的新增、删除与修改。 最极端的情况,ignoreChange与上面的pattern一致,即会完全忽略所有资源的修改。 |
| largeModSize | 100 | 对于修改的资源,如果大于largeModSize,我们将使用bsdiff算法。这可以降低补丁包的大小,但是会增加合成时的复杂度。默认大小为100kb |
packageConfig | 用于生成补丁包中的'package_meta.txt'文件 | |
| configField | TINKER_ID, NEW_TINKER_ID | configField("key", "value"), 默认我们自动从基准安装包与新安装包的Manifest中读取tinkerId,并自动写入configField。在这里,你可以定义其他的信息,在运行时可以通过TinkerLoadResult.getPackageConfigByName得到相应的数值。但是建议直接通过修改代码来实现,例如BuildConfig。 |
sevenZip | 7zip路径配置项,执行前提是useSign为true | |
| zipArtifact | null | 例如"com.tencent.mm:SevenZip:1.1.10",将自动根据机器属性获得对应的7za运行文件,推荐使用。 |
| path | 7za | 系统中的7za路径,例如"/usr/local/bin/7za"。path设置会覆盖zipArtifact,若都不设置,将直接使用7za去尝试。 |
apply plugin: 'com.android.application' def javaVersion = JavaVersion.VERSION_1_7 def bakPath = file("${buildDir}/bakApk/") //指定基准文件存放位置 android { compileSdkVersion 25 buildToolsVersion "25.0.2" defaultConfig { applicationId "com.example.mytinker" minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" multiDexEnabled true } sourceSets { main { jniLibs.srcDirs = ['libs'] } } compileOptions { sourceCompatibility javaVersion targetCompatibility javaVersion } //recommend dexOptions { jumboMode = true } signingConfigs{ release{ try { storeFile file("zhengwanshi_signing.jks") storePassword "z3115002510" keyAlias "MyAlias" keyPassword "z3115002510" }catch(ex){ throw new InvalidUserDataException(ex.toString()) } } } buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.release } } //真正的多渠道脚本支持 productFlavors { googleplayer { manifestPlaceholders = [UMENG_CHANNEL_VALUE: "googleplayer"] } baidu { manifestPlaceholders = [UMENG_CHANNEL_VALUE: "baidu"] } productFlavors.all { flavor -> flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name] } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.3.1' testCompile 'junit:junit:4.12' //可选,用于生成application类 provided('com.tencent.tinker:tinker-android-anno:1.9.1') //tinker的核心库 compile('com.tencent.tinker:tinker-android-lib:1.9.1') compile "com.android.support:multidex:1.0.1" } ext { tinkerEnable = true tinkerOldApkPath = "${bakPath}/app-release-0423-00-08-03.apk" tinkerID = "1.0" tinkerApplyMappingPath = "${bakPath}/app-release-0423-00-08-03-mapping.txt" tinkerApplyResourcePath = "${bakPath}/app-release-0423-00-08-03-R.txt" tinkerBuildFlavorDirectory = "${bakPath}/app-0511-12-36-20" } def buildWithTinker() { return ext.tinkerEnable } def getOldApkPath() { return ext.tinkerOldApkPath } def getApplyMappingPath() { return ext.tinkerApplyMappingPath } def getApplyResourceMappingPath() { return ext.tinkerApplyResourcePath } def getTinkerIdValue() { return ext.tinkerID } def getTinkerBuildFlavorDirectory(){ return ext.tinkerBuildFlavorDirectory } if (buildWithTinker()) { //启用tinker apply plugin: 'com.tencent.tinker.patch' //所有tinker相关的参数配置 tinkerPatch { oldApk = getOldApkPath() //指定old apk文件径 ignoreWarning = false //不忽略tinker的警告,有则中止patch文件的生成 useSign = true //强制patch文件也使用签名 tinkerEnable = buildWithTinker(); //指定是否启用tinker buildConfig { applyMapping = getApplyMappingPath() //指定old apk打包时所使用的混淆文件 applyResourceMapping = getApplyResourceMappingPath() //指定old apk的资源文件 tinkerId = getTinkerIdValue() //指定TinkerID keepDexApply = false } dex { dexMode = "jar" //jar、raw pattern = ["classes*.dex", "assets/secondary-dex-?.jar"] //指定dex文件目录 loader = ["com.imooc.tinker.MyTinkerApplication"] //指定加载patch文件时用到的类 } lib { pattern = ["libs/*/*.so"] } res { pattern = ["res/*", "assets/*", "resources.arcs", "AndoridManifest.xml"] //指定tinker可以修改的资源路径 ignoreChange = ["assets/sample_meta.txt"] //指定不受影响的资源路径 largeModSize = 100 //资源修改大小默认值 } packageConfig { configField("patchMessage", "fix the 1.0 version's bugs") configField("patchVersion", "1.0") } } List<String> flavors = new ArrayList<>(); project.android.productFlavors.each { flavor -> flavors.add(flavor.name) } boolean hasFlavors = flavors.size() > 0 /** * 复制基准包和其它必须文件到指定目录 */ android.applicationVariants.all { variant -> /** * task type, you want to bak */ def taskName = variant.name def date = new Date().format("MMdd-HH-mm-ss") 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.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 { 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" } } } } } }
配置好后在Terminal中输入gradlew assembleRelease 生成Old.apk和复杂混淆文件和资源文件到bakApk文件夹下

在修改Bug过后点击Gradle选项卡,选择tinkerPatchRelease生成补丁apk

运行结果

接下来就是怎么下载到手机修复了
看看修复效果
修复前

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="加载patch文件" android:textSize="24sp" android:onClick="loadPatch"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="成功加载patch文件" android:textSize="24sp" /> </LinearLayout>
修复后:
<Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="加载patch文件" android:textSize="24sp" android:onClick="loadPatch"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="成功加载patch文件" android:textSize="24sp" />

本文介绍Tinker热更新方案的特点及优势,对比AndFix、Robust等方案,并提供详细的使用教程,包括Gradle配置、命令行操作及示例代码。
488

被折叠的 条评论
为什么被折叠?



