背景:
因为项目要接入热修复功能,最开始选择了腾讯Bugly,毕竟有微信那么大的用户体量作背书,而且提供了版本管理平台方便版本维护。照着官方文档和Github的Issues的帮助,费了一番功夫总算接入成功,并且打基准包安装和上传补丁包修复成功。
本来挺高兴的,但......我们AndroidStudio用的是北极狐版本,而且项目使用的Gradle和AGP都是7.0版本。当时Tinker官方版本都不支持AGP7.0。好在等了一周,在2022年1月份微信更新了版本v1.9.14.19 支持了AGP7.0和R8。但是Bugly上次更新还是2021年的上半年,更新支持已经不知道何年何月了。所以我转而只接入微信Tinker,本文也只讲述本次接入所遇到的问题和解决办法。在服务器上进行版本管理维护暂不处理。
开发环境:
- Window10-64位(因为也用Mac M1开发,所以问题方面的解决也有涉及M1芯片相关的。)
- AndroidStudio BumbleBee build February 2,2022
- Gradle Version 7.2
- AGP Version 7.1.0
- 项目compileSdk和targetSdk都为31(涉及到的有加载补丁包没有权限问题)
正式接入:
一、SDK接入:
(1)插件依赖,项目的build.gradle文件中添加如下内容:
buildscript {
dependencies {
classpath ("com.tencent.tinker:tinker-patch-gradle-plugin:1.9.14.19")
}
}
⚠️注意:
- 插件版本为1.9.14.19,最新版本可以查看链接插件版本 ,下的最新版本,注意:排序并非按照版本顺序,注意发布时间。
-
代码块添加在“plugins {}”代码块之前,不然会提示错误信息“all buildscript {} blocks must appear before any plugins {} blocks in the script”。
(2)app目录下的build.gradle引入如下依赖:
//dex分包
implementation "androidx.multidex:multidex:2.0.1"
//可选,用于生成application类
annotationProcessor('com.tencent.tinker:tinker-android-anno:1.9.14.19')
compileOnly('com.tencent.tinker:tinker-android-anno:1.9.14.19')
//tinker的核心库
implementation('com.tencent.tinker:tinker-android-lib:1.9.14.19')
⚠️注意:依赖的版本通常是和第一步的插件版本一致的,具体版本可查看链接依赖版本。
(3)引入插件:
apply plugin: 'com.tencent.tinker.patch'
(4)项目的gradle.properties文件添加如下属性:
TINKER_ID = 1.0
⚠️注意:tinkerId一般为每次发版的版本号,补丁包是根据tinkerId匹配基准包的。之后会在app的build.gradle当中引用该属性。
(5)将官方demo中的文件【tinker_multidexkeep.pro】拷贝到自己项目的app目录下。
⚠️注意:该文件内有一处需要修改成自己内容的地方,需要将该文件内替换为自己在继承自“DefaultApplicationLike”类中声明的application。如下:
(6)在官方demo中,将打包的配置都写在了app下的build.gradle当中,这里将这些内容独立出来,app目录下创建tinker.gradle文件。并在app下的build.gradle中引入:
// 引入tinker配置
apply from: "tinker.gradle"
因为官方demo当中的gradle语法属性有些已经废弃了,所以【tinker.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
//打补丁包时候这里配置基准包的全称
tinkerOldApkPath = "${bakPath}/app-debug-0211-11-33-02.apk"
//打Release补丁包时候这里配置基准包时候生成的mapping文件proguard mapping file to build //patch apk
tinkerApplyMappingPath = "${bakPath}/"
//打补丁包时候这里配置基准包时候生成的文件全称resource R.txt to build patch apk, must input //if there is resource changed
tinkerApplyResourcePath = "${bakPath}/app-debug-0211-11-33-02-R.txt"
//多渠道包时候的输出目录only use for build all flavor, if not, just ignore this field
tinkerBuildFlavorDirectory = "${bakPath}/app-1018-17-32-47"
}
def gitSha() {
try {
String gitRev = 'git rev-parse --short HEAD'.execute(null, project.rootDir).text.trim()
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 getOldApkPath() {
return hasProperty("OLD_APK") ? OLD_APK : ext.tinkerOldApkPath
}
def getApplyMappingPath() {
return hasProperty("APPLY_MAPPING") ? APPLY_MAPPING : ext.tinkerApplyMappingPath
}
def getApplyResourceMappingPath() {
return hasProperty("APPLY_RESOURCE") ? APPLY_RESOURCE : ext.tinkerApplyResourcePath
}
def getTinkerIdValue() {
return hasProperty("TINKER_ID") ? TINKER_ID : gitSha()
}
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 = getOldApkPath()
/**
* optional,default 'false'
* there are some cases we may get some warnings
* if ignoreWarning is true, we would just assert the patch process
* case 1: minSdkVersion is below 14, but you are using dexMode with raw.
* it must be crash when load.
* case 2: newly added Android Component in AndroidManifest.xml,
* it must be crash when load.
* case 3: loader classes in dex.loader{} are not keep in the main dex,
* it must be let tinker not work.
* case 4: loader classes in dex.loader{} changes,
* loader classes is ues to load patch dex. it is useless to change them.
* it won't crash, but these changes can't effect. you may ignore it
* case 5: resources.arsc has changed, but we don't use applyResourceMapping to build
*/
ignoreWarning = false
/**
* 报错解决:Warning:ignoreWarning is false,
* but we found loader classes are found in old secondary dex
*/
allowLoaderInAnyDex = true
removeLoaderForAllDex = true
/**
* optional,default 'true'
* whether sign the patch file
* if not, you must do yourself. otherwise it can't check success during the patch loading
* we will use the sign config with your build type
*/
useSign = true
/**
* 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 = getTinkerIdValue()
/**
* if keepDexApply is true, class in which dex refer to the old apk.
* open this can reduce the dex diff file size.
*/
keepDexApply = false
/**
* optional, default 'false'
* Whether tinker should treat the base apk as the one being protected by app
* protection tools.
* If this attribute is true, the generated patch package will contain a
* dex including all changed classes instead of any dexdiff patch-info files.
*/
isProtectedApp = false
/**
* optional, default 'false'
* Whether tinker should support component hotplug (add new component dynamically).
* If this attribute is true, the component added in new apk will be available after
* patch is successfully loaded. Otherwise an error would be announced when generating patch
* on compile-time.
*
* <b>Notice that currently this feature is incubating and only support NON-EXPORTED Activity</b>
*/
supportHotplugComponent = false
}
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.2.17"
/**
* 设置path之后会覆盖zipArtifact的配置,使用本地
* optional,default '7za'
* you can specify the 7za path yourself, it will overwrite the zipArtifact value
*/
path = "/Users/pary/.gradle/caches/modules-2/files-2.1/com.tencent.mm/SevenZip/1.2.17"
}
}
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
if (variant.metaClass.hasProperty(variant, 'packageApplicationProvider')) {
def packageAndroidArtifact = variant.packageApplicationProvider.get()
if (packageAndroidArtifact != null) {
try {
from new File(packageAndroidArtifact.outputDirectory.getAsFile().get(), variant.outputs.first().variantOutput.outputFileName.get())
} catch (Exception e) {
from new File(packageAndroidArtifact.outputDirectory, variant.outputs.first().variantOutput.outputFileName.get())
}
} else {
from variant.outputs.first().mainOutputFile.outputFile
}
} else {
from variant.outputs.first().outputFile
}
into destPath
rename { String fileName ->
fileName.replace("${fileNamePrefix}.apk", "${newFileNamePrefix}.apk")
}
def dirName = variant.dirName
if (hasFlavors) {
dirName = taskName
}
from "${buildDir}/outputs/mapping/${dirName}/mapping.txt"
into destPath
rename { String fileName ->
fileName.replace("mapping.txt", "${newFileNamePrefix}-mapping.txt")
}
from "${buildDir}/intermediates/symbols/${dirName}/R.txt"
from "${buildDir}/intermediates/symbol_list/${dirName}/R.txt"
from "${buildDir}/intermediates/runtime_symbol_list/${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"
}
}
}
}
}
}
⚠️注意:在上边的文件中,相比于官方Demo,已经修改了三处内容,因为不修改的话,打包会报错,下边列出了修改的具体内容:
-
在tinkerPatch{}中增加如下两个属性配置,不添加的话会有报错信息:Warning:ignoreWarning is false,but we found loader classes are found in old secondary dex。
allowLoaderInAnyDex = true removeLoaderForAllDex = true
- it.doLast{}当中修改了官方demo中的属性:
//官方demo报错的属性方法: variant.outputs.first().apkData.outputFileName //可以正常使用的方法: variant.outputs.first().variantOutput.outputFileName.get()
- sevenZip{}中配置的在打补丁包时候使用的SevenZip配置 :
//官方demo的原来配置如下: zipArtifact = "com.tencent.mm:SevenZip:1.1.10"
这样打补丁包会报如下错误:
这是因为版本1.1.10已经不存在了,最新的版本可以查看如下链接下最新的版本:版本链接 ,替换为最新版本1.2.17之后,又报如下错误:
因为SevenZip会根据系统选择对应的exe可执行文件,但是在这个目录下版本目录链接 没有系统对应的可执行程序,所以报错。既然远程没有对应的exe文件,那么我们可以使用本地的路径。
-
Mac控制台输入“open .gradle”打开本地gradle路径找到【com.tencent.mm】,查看其路径下是否有SevenZip文件夹以及具体的版本文件夹,如图:
-
Windows系统可以在【系统盘/用户/账户名/.gradle】下找到对应的文件夹
如果有的话,可以在tinker.gradle的sevenZip{}中配置如下path,会覆盖zipArtifact 的在线配置:
path = "/Users/pary/.gradle/caches/modules-2/files-2.1/com.tencent.mm/SevenZip/1.2.17"
此时根据基准包打补丁包,会成功build,但是还是会有报错信息输出,如下:
因为在上边设置的本地路径下并没有对应的SevenZip程序,所以7za压缩打包apk出错,也就没有在对应的目录下生成patch_signed.apk文件。但是此时已经有补丁包了,在此目录下:
这个apk也是生成的补丁包,7za的主要是压缩生成的补丁包大小,缩减体积,但是如果7za不小心给反向压缩了,Tinker也会提示你使用体积较小的apk文件。
(7) 修改app下的build.gradle内容,需要添加的内容如下:
-
在android{}中添加以下内容
// tinker支持大工程文件配置 dexOptions { jumboMode = true }
- 在defaultConfig{}中添加如下内容
multiDexEnabled true multiDexKeepProguard file("tinker_multidexkeep.pro") buildConfigField "String", "MESSAGE", "\"I am the base apk\"" buildConfigField "String", "TINKER_ID", "\"${TINKER_ID}\"" buildConfigField "String", "PLATFORM", "\"all\""
二、代码接入:
(1)从官方demo中拷贝如下文件到自己的项目:
-
crash\reporter\service三个文件夹内的全部文件,并在清单文件引入SampleResultService
<service android:name=".service.SampleResultService" android:permission="android.permission.BIND_JOB_SERVICE" android:exported="false"/>
- app包内部的BuildInfo类。
-
util包内部的Utils、TinkerManager两个类。
(2)自定义Application代理类:
- 创建继承自DefaultApplicationLike的类,如下:
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import androidx.multidex.MultiDex;
import com.tencent.tinker.anno.DefaultLifeCycle;
import com.tencent.tinker.entry.DefaultApplicationLike;
import com.tencent.tinker.lib.tinker.Tinker;
import com.tencent.tinker.loader.shareutil.ShareConstants;
//注解关联MyApplicaiton:这里的applicaiton不能为MyApplication,否则会报已存在类。
@DefaultLifeCycle(application = "com.example.tinkerwei.Application",
flags = ShareConstants.TINKER_ENABLE_ALL)
public class SampleApplicationLike extends DefaultApplicationLike {
public SampleApplicationLike(Application application, int tinkerFlags, boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime, long applicationStartMillisTime, Intent tinkerResultIntent) {
super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
}
@Override
public void onCreate() {
super.onCreate();
// 可以在这里初始化SDK
}
@Override
public void onBaseContextAttached(Context base) {
super.onBaseContextAttached(base);
MultiDex.install(base);
TinkerManager.setTinkerApplicationLike(this);
TinkerManager.setUpgradeRetryEnable(true);
TinkerManager.installTinker(this);
Tinker.with(getApplication());
}
}
- 创建继承自TinkerApplication的类,如下:
import com.tencent.tinker.loader.app.TinkerApplication;
import com.tencent.tinker.loader.shareutil.ShareConstants;
public class MyApplication extends TinkerApplication {
public MyApplication() {
//注意第二个参数为自定义的SampleApplicationLike的路径
super(ShareConstants.TINKER_ENABLE_ALL,
"com.example.tinkerwei.app.SampleApplicationLike",
"com.tencent.tinker.loader.TinkerLoader",
false, false);
}
}
- 创建继承自TinkerApplication的类,如下:
三、编写加载补丁包的代码:
(1)检查应用的读写文件权限,没有权限请求权限。示例:
// 请求读文件权限
private void requestPermission() {
if (!checkPermission()) {
ActivityCompat.requestPermissions(this,
new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
}
// 检查是否有读文件权限
private boolean checkPermission() {
final int res = ContextCompat.checkSelfPermission(this.getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE);
return res == PackageManager.PERMISSION_GRANTED;
}
⚠️注意:如果加载补丁时候报如下错误(主要针对Android10+版本):
open failed:EACCES(Permission denied)
则需要在清单文件application标签下添加如下属性:
android:requestLegacyExternalStorage="true"
(2)点击按钮加载本地补丁包代码,如下:
findViewById(R.id.btnLoad).setOnClickListener(v -> {
String pathRootPatchApk = Environment.getExternalStorageDirectory() +
File.separator + "app-debug-patch_signed.apk";
File fileApk = new File(pathRootPatchApk);
Log.i("Tinker", "补丁文件路径:" + pathRootPatchApk);
Log.i("Tinker", "补丁文件是否存在:" + fileApk.exists());
TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(), pathRootPatchApk);
});
⚠️注意:因为这里是读取的SDK根目录的apk补丁文件,所以对于Android10+的版本会出现上一步当中的打开文件没有权限错误。
四、Gradle打包:
(1)打基准包,如图:
打包完成之后将会在build文件夹生成如下内容:
其中bakApk包中的内容是需要在打补丁包之前在tinker.gradle进行配置的,如下图:
红框和蓝框处是需要替换bakApk文件夹的内容的,蓝框处是开启混淆之后会生成的mapping文件替换处。
绿色框处是打多渠道包处的输出文件目录。
(2)打修复bug补丁包,打补丁包之前可代码设置打印内容或者显示一个控件。
打包之后会在app/build文件夹下生成对应的补丁包,具体路径如下:
因为我打的是debug包,所以这里生成的是debug文件夹下的补丁包app-debug-patch_signed.apk。
然后将这个补丁包拷贝到手机上之前编写加载补丁包代码时候定义的路径对应的位置。
补丁加载成功的话会有如下提示信息:
如果成功,应用上的tinker sdk也会toast提示重启应用进程来运行最新的应用。(上图的红色报错是因为补丁加载成功后会自动删除补丁包,这里没有删除成功,所以报错,并不影响补丁的成功应用。)