項目越做越大,總是省不了熱修復這個點丸升,畢竟測試人員再仔細铆农,還是有幾率漏掉bug,或者壓根就是產(chǎn)品抽風,已經(jīng)上線的東西還非要做些更改墩剖『锇迹總之,熱修復是所有程序員繞不過去的一個點岭皂。
還好已經(jīng)有大廠提前幫我們鋪好了這條路郊霎,不用費太多工夫。
我們的項目選擇接入騰訊的Tinker爷绘,畢竟有的用戶可能沒錢逛淘寶(阿里的 AndFix)书劝,用不到美團(美團的 Robust),但他們都會用微信土至,微信作為社交軟件购对,占領(lǐng)了大部分用戶的手機。
這篇文字主要是把我集成Tinker的過程展示出來陶因,并且記錄下我遇到的幾個坑骡苞,具體深入的原理以及細節(jié),可以去Tinker的Github查閱相關(guān)資料楷扬。
對了解幽,篇幅量看著挺大,其實沒多少東西烘苹,都是復制的代碼躲株,所以請放心食用,很簡單的镣衡。
1霜定,添加依賴以及
打開Tinker的Github,像往常添加三方庫那樣廊鸥,將依賴添加到項目中然爆。
project的build.gradle
dependencies {
...
classpath('com.tencent.tinker:tinker-patch-gradle-plugin:1.9.1')
...
}
app的build.gradle
dependencies {
...
//可選,用于生成application類
compileOnly 'com.tencent.tinker:tinker-android-anno:1.9.1'
//tinker的核心庫
implementation 'com.tencent.tinker:tinker-android-lib:1.9.1'
annotationProcessor 'com.tencent.tinker:tinker-android-anno:1.9.1'
// 合并的時候需要
implementation "com.android.support:multidex:1.0.3"
...
}
如果在Demo中添加熱更新的話(沒有人會把不熟練的東西直接往項目里丟吧黍图?)曾雕,記得添加SD卡讀寫權(quán)限,畢竟是要來讀取Patch包的助被。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
接下來配置Tinker的配置項剖张,寫在app的build.gradle中。
可以直接復制下面的代碼揩环,下面的代碼基于官方Demo做了一點修改搔弄,刪掉了gitSha()方法。
或者從Tinker的Demo的build.gradle中復制過來丰滑,但請記得修改官方代碼中ignoreWarning = false顾犹,改為true,否則不執(zhí)行熱修復。
//----------------------------------tinker配置--------------------------
def bakPath = file("${buildDir}/bakApk/")
//刪掉了gitSha()方法炫刷,是從git獲取版本號的方法
ext {
tinkerEnabled = true
tinkerOldApkPath = "${bakPath}/app-debug-0424-15-02-56.apk"
tinkerApplyMappingPath = "${bakPath}/app-debug-1018-17-32-47-mapping.txt"
tinkerApplyResourcePath = "${bakPath}/app-debug-0424-15-02-56-R.txt"
tinkerBuildFlavorDirectory = "${bakPath}/app-1018-17-32-47"
}
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()
// 必須把TINKER_ID寫死在gradle.properties中擎宝,而且刪掉了gitSha()方法,是從git獲取版本號的方法
return TINKER_ID
}
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
/**
* 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.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
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().apkData.outputFileName)
} catch (Exception e) {
from new File(packageAndroidArtifact.outputDirectory, variant.outputs.first().apkData.outputFileName)
}
} else {
from variant.outputs.first().mainOutputFile.outputFile
}
} else {
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"
from "${buildDir}/intermediates/symbol_list/${variant.dirName}/R.txt"
from "${buildDir}/intermediates/runtime_symbol_list/${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"
}
}
}
}
}
}
//----------------------------------tinker配置--------------------------
然后還有在項目的gradle.properties中添加,同樣的甚垦,有官方Demo的地址gradle.properties
TINKER_VERSION=1.9.8
TINKER_ID=1.0
# TINKER_ID是區(qū)分增量/完整包的關(guān)鍵變量
OLD_APK=D\:\\Java\\other\\TinkerTest\\app\\build\\bakApk\\app-debug-16-50.apk
# OLD_APK可以刪除茶鹃,是方便更改apk名的方法,這個下面會說到
配置基本就到這里艰亮,接下來是代碼的部分闭翩。
2拜银,代碼
接下來是代碼部分陷遮,首先,是生成Application李命,如果要使用Tinker熱更新侄非,就必須使用它生成的Application類蕉汪。
此時,我們就有一個工具類逞怨,用來生成Application
@DefaultLifeCycle(
application = "你的包名.MyApp", //這里填寫包名和你想要生成的Application類名者疤,tinker會自動生成該類
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();
}
@Override
public void onBaseContextAttached(Context base) {
super.onBaseContextAttached(base);
MultiDex.install(base);
TinkerInstaller.install(this);
}
}
build項目之后,把android:name=".MyApp"寫進AndroidManifest
<application
android:name=".MyApp"
...
</application>
接下來叠赦,你可以寫一個你喜歡的布局驹马,但記得留一個Button來激活熱修復。
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TinkerInstaller.onReceiveUpgradePatch(getApplication().getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed");
}
});
此時編譯,運行糯累,前期準備工作就算完成了算利。
這時候運行項目點擊按鈕時沒有任何反應的,因為增量包還沒有放上去寇蚊。
3笔时,熱修復部分
接下來我們準備生成增量包的部分。
到這時候仗岸,我們可以認為項目已經(jīng)發(fā)布并且被用戶安裝(安裝到測試機)允耿,假定我們現(xiàn)在也有個bug,需要修改button的文字扒怖。
此時切換到project視圖较锡,在如圖所示目錄下,能看到一個以時間戳命名的apk包盗痒,我們叫他基準包蚂蕴。它就是剛剛安裝到手機上的那個有bug的包。
重要:這個包名的生成規(guī)則俯邓,在app的build.gradle中搜索"MMdd-HH-mm-ss"可以看到骡楼,此處可以修改,但是一定要保證每次生成的包名都有不同稽鞭,否則可能會造成熱修復無法生效的問題鸟整。
現(xiàn)在要通過熱更新的方式對這個app進行修改,首先朦蕴,要把基準包的包命復制到
app的build.gradle文件中
ext {
...
tinkerOldApkPath = "${bakPath}/app-debug-0424-15-02-56.apk"http://這個位置
...
}
如果你在gradle.properties文件中定義了OLD_APK篮条,那就必須寫在OLD_APK這個位置,不過記得把文件路徑換成你自己的
OLD_APK=D\:\\Java\\other\\TinkerAgain\\app\\build\\bakApk\\app-debug-16-50.apk
我比較推薦第二種這個寫法吩抓,位置好找涉茧,并且不會因為誤刪build.gradle代碼造成其他問題
放一張圖,看起來直觀一些疹娶。
修改完成同步之后伴栓,修改Activity中的代碼,比如
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TinkerInstaller.onReceiveUpgradePatch(getApplication().getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed");
}
});
button.setText("修改文字");
修改剛才button中的文字雨饺,之后找到如圖所示路徑挣饥,雙擊開始生成差異包
看到BUILD SUCCESSFUL就說明成功了,此時在如圖目錄會生成一個差異包沛膳。
將差異包復制到桌面扔枫, 改名(我代碼里寫的是patch_signed),然后復制到手機根目錄锹安,點擊按鈕短荐。
等待幾秒之后倚舀,app會直接退出,再次打開就是熱修復完成的樣子了忍宋。
4痕貌,要注意的地方
1,讀寫權(quán)限
一定要記得開SD卡讀寫權(quán)限糠排,否則全部做對了舵稠,但是程序讀不到差異包也不會生效。
表現(xiàn)出來的樣子是點擊按鈕沒反應入宦。
跟著走下來哺徊,但是沒生效的話,大概率是權(quán)限問題乾闰。
2落追,基準包的命名
就是在app的build.gradle中
if (buildWithTinker()) {
...
def date = new Date().format("MMdd-HH-mm-ss")
...
}
這個時間格式會影響命名,具體來說會影響app-debug-XXX.apk中間的部分涯肩,上面也說過轿钠,這個位置可以改,但是一定要保證每次生成的包名都有不同病苗,否則可能會造成熱修復無法生效的問題疗垛。
網(wǎng)上有人說,這個位置改成諸如def date = new Date().format("123")這個形式可以避免生成太多的包硫朦,看起來不亂贷腕,但是這樣的話,由于無法通過命名區(qū)分每次的包阵幸,所以會出現(xiàn)差異包無法合并到現(xiàn)有app中的問題。
表現(xiàn)出來的樣子是芽世,應用被強制關(guān)閉了挚赊,但是再次打開的時候還是之前的樣子。
另外济瓢,修改包名在
tinkerOldApkPath = "${bakPath}/app-debug-0424-15-02-56.apk"
OLD_APK=D\:\\Java\\other\\TinkerTest\\app\\build\\bakApk\\app-debug-0424-15-02-56.apk
這兩個位置都可以荠割,我建議用OLD_APK的方式,好處剛才也說過了旺矾,不亂蔑鹦,并且不會誤刪。
但是直接在tinkerOldApkPath更新也是可以的箕宙,但是這樣的話記得把gradle.properties文件中OLD_APK這一行刪掉嚎朽,其它地方不用動。因為代碼里會有一個判斷語句柬帕。
def getOldApkPath() {
return hasProperty("OLD_APK") ? OLD_APK : ext.tinkerOldApkPath
}
3哟忍,更新全量包
通過熱修復更改過應用后狡门,如果通過正常途徑安裝新的版本,頁面是不會生效的锅很,還是保持熱修復之后的樣子其馏。
更新全量包的時候,需要更新gradle.properties文件中的變量爆安,TINKER_ID=1.0
這個地方可以使TINKER_ID跟App版本號保持一致叛复,以免忘記。
個人理解扔仓,難免有錯誤紕漏褐奥,歡迎指正。轉(zhuǎn)載請注明出處当辐。