前言: Tinker 是一个开源项目(Github链接),它是微信官方的Android热补丁解决方案,它支持动态下发代码、So库以及资源,让应用能够在不需要重新安装的情况下实现更新。
1.1 Gradle 接入
在项目的build.gradle中添加 tinker-patch-gradle-plugin的依赖
在app的build.gradle中添加tinker的库依赖以及apply tinker 的gradle plugin
1.2 Tinker Gradle 配置
参考 Tinker 接入指南
tinkerPatch 全局配置示例
1.3 Patch 生成
- 执行assemble任务,生成 oldApk
- 修改代码,bug 修复,资源文件修改等等
- 修改gradle tinkerPatch 配置,oldApk applyMapping及applyResourceMapping (混淆 mapping 和R文件使用同一份)
- 执行 tinkerPatch task 生成patch文件
apk路径,mapping 路径,R.txt 路径 示例代码
|
|
1.4 Tinker patch 加载
1.4.1 改造Application类(实现补丁包可以对Application做修改),两种方式(建议使用注解的方式):
- (1)定义代理类实现DefaultApplicationLike
Tinker自定义扩展 - (2)Annotation 方式,需要引入 tinker-android-anno。保证无法修改Application,避免误操作
123456@DefaultLifeCycle(application = ".SampleApplication", //application类名flags = ShareConstants.TINKER_ENABLE_ALL, //tinkerFlagsloaderClass = "com.tencent.tinker.loader.TinkerLoader", //loaderClassName, 我们这里使用默认即可!loadVerifyFlag = false) //tinkerLoadVerifyFlagpublic class SampleApplicationLike extends DefaultApplicationLike- (1)定义代理类实现DefaultApplicationLike
注:将原来的application类删掉,初始化操作全部放在代理类中。
1.4.2 gradle tinker patch 配置
12345dex {loader = ["com.tencent.tinker.loader.*",// 配置成自己的application"tinker.sample.android.YourApplication",}1.4.3 安装tinker
12345678910111213141516171819202122232425262728@SuppressWarnings("unused")@DefaultLifeCycle(application = "tinker.sample.android.app.SampleApplication",flags = ShareConstants.TINKER_ENABLE_ALL,loadVerifyFlag = false)public class SampleApplicationLike extends DefaultApplicationLike {private static final String TAG = "Tinker.SampleApplicationLike";public SampleApplicationLike(Application application, int tinkerFlags, boolean tinkerLoadVerifyFlag,long applicationStartElapsedTime, long applicationStartMillisTime, Intent tinkerResultIntent,Resources[] resources, ClassLoader[] classLoader, AssetManager[] assetManager) {super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent, resources, classLoader, assetManager);}@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)@Overridepublic void onBaseContextAttached(Context base) {super.onBaseContextAttached(base);MultiDex.install(base);SampleApplicationContext.application = getApplication();SampleApplicationContext.context = getApplication();//installTinker after load multiDex//or you can put com.tencent.tinker.** to main dexTinkerInstaller.install(this);}}1.4.4 加载补丁
将生成的补丁包,推送到指定目录,运行app时调用下面的代码进行加载。1TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed_7zip.apk");
在实际开发过程中,我们是需要将补丁存到服务器,由服务器进行补丁分发,Tinker的开发团队已经提供,集成文档很详细,我就不做搬运工了。Tinker Server SDK集成文档