一、概述
放了一個大長假,happy,先祝大家2017年笑口常開。
假期中一行程式碼沒寫,但是想著馬上要上班了,趕緊寫篇部落格回顧下技能,於是便有了本文。
熱修復這項技術,基本上已經成為專案比較重要的模組了。主要因為專案在上線之後,都難免會有各種問題,而依靠發版去修復問題,成本太高了。
現在熱修復的技術基本上有阿里的AndFix、QZone的方案、美團提出的思想方案以及騰訊的Tinker等。
其中AndFix可能接入是最簡單的一個(和Tinker命令列接入方式差不多),不過相容性還是是有一定的問題的;QZone方案對效能會有一定的影響,且在Art模式下出現記憶體錯亂的問題(其實這個問題我之前並不清楚,主要是tinker在MDCC上指出的);美團提出的思想方案主要是基於Instant Run的原理,目前尚未開源,不過這個方案我還是蠻喜歡的,主要是相容性好。
這麼看來,如果選擇開源方案,tinker目前是最佳的選擇,tinker的介紹有這麼一句:
Tinker已執行在微信的數億Android裝置上,那麼為什麼你不使用Tinker呢?
好了,說了這麼多,下面來看看tinker如何接入,以及tinker的大致的原理分析。希望通過本文可以實現幫助大家更好的接入tinker,以及去了解tinker的一個大致的原理。
二、接入Tinker
接入tinker目前給了兩種方式,一種是基於命令列的方式,類似於AndFix的接入方式;一種就是gradle的方式。
考慮早期使用Andfix的app應該挺多的,以及很多人對gradle的相關配置還是覺得比較繁瑣的,下面對兩種方式都介紹下。
(1)命令列接入
接入之前我們先考慮下,接入的話,正常需要的前提(開啟混淆的狀態)。
最後就是看看這個專案有沒有需要配置混淆;
有了大致的概念,我們就基本瞭解命令列接入tinker,大致需要哪些步驟了。
依賴引入
dependencies {
// ...
//可選,用於生成application類
provided('com.tencent.tinker:tinker-android-anno:1.7.7')
//tinker的核心庫
compile('com.tencent.tinker:tinker-android-lib:1.7.7')
}
順便加一下簽名的配置:
android{
//...
signingConfigs {
release {
try {
storeFile file("release.keystore")
storePassword "testres"
keyAlias "testres"
keyPassword "testres"
} catch (ex) {
throw new InvalidUserDataException(ex.toString())
}
}
}
buildTypes {
release {
minifyEnabled true
signingConfig signingConfigs.release
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
debuggable true
minifyEnabled true
signingConfig signingConfigs.release
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
文末會有demo的下載地址,可以直接參考build.gradle檔案,不用擔心這些簽名檔案去哪找。
API引入
API主要就是初始化和loadPacth。
正常情況下,我們會考慮在Application的onCreate中去初始化,不過tinker推薦下面的寫法:
@DefaultLifeCycle(application = ".SimpleTinkerInApplication",
flags = ShareConstants.TINKER_ENABLE_ALL,
loadVerifyFlag = false)
public class SimpleTinkerInApplicationLike extends ApplicationLike {
public SimpleTinkerInApplicationLike(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);
}
@Override
public void onCreate() {
super.onCreate();
TinkerInstaller.install(this);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
ApplicationLike通過名字你可能會猜,並非是Application的子類,而是一個類似Application的類。
tinker建議編寫一個ApplicationLike的子類,你可以當成Application去使用,注意頂部的註解:@DefaultLifeCycle
,其application屬性,會在編譯期生成一個SimpleTinkerInApplication
類。
所以,雖然我們這麼寫了,但是實際上Application會在編譯期生成,所以AndroidManifest.xml
中是這樣的:
<application
android:name=".SimpleTinkerInApplication"
.../>
編寫如果報紅,可以build下。
這樣其實也能猜出來,這個註解背後有個Annotation Processor在做處理,如果你沒了解過,可以看下:
通過該文會對一個編譯時註解的執行流程和基本API有一定的掌握,文中也會對tinker該部分的原始碼做解析。
上述,就完成了tinker的初始化,那麼呼叫loadPatch的時機,我們直接在Activity中新增一個Button設定:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void loadPatch(View view) {
TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(),
Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed.apk");
}
}
我們會將patch檔案直接push到sdcard根目錄;
所以一定要注意:新增SDCard許可權,如果你是6.x以上的系統,自己新增上授權程式碼,或者手動在設定頁面開啟SDCard讀寫許可權。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
除以以外,有個特殊的地方就是tinker需要在AndroidManifest.xml
中指定TINKER_ID。
<application>
<meta-data
android:name="TINKER_ID"
android:value="tinker_id_6235657" />
//...
</application>
到此API相關的就結束了,剩下的就是考慮patch如何生成。
patch生成
tinker提供了patch生成的工具,原始碼見:tinker-patch-cli,打成一個jar就可以使用,並且提供了命令列相關的引數以及檔案。
命令列如下:
java -jar tinker-patch-cli-1.7.7.jar -old old.apk -new new.apk -config tinker_config.xml -out output
需要注意的就是tinker_config.xml
,裡面包含tinker的配置,例如簽名檔案等。
這裡我們直接使用tinker提供的簽名檔案,所以不需要做修改,不過裡面有個Application的item修改為與本例一致:
<loader value="com.zhy.tinkersimplein.SimpleTinkerInApplication"/>
大致的檔案結構如下:
可以在tinker-patch-cli中提取,或者直接下載文末的例子。
上述介紹了patch生成的命令,最後需要注意的就是,在第一次打出apk的時候,保留下生成的mapping檔案,在/build/outputs/mapping/release/mapping.txt
。
可以copy到與proguard-rules.pro
同目錄,同時在第二次打修復包的時候,在proguard-rules.pro
中新增上:
-applymapping mapping.txt
保證後續的打包與線上包使用的是同一個mapping檔案。
tinker本身的混淆相關配置,可以參考:
如果,你對該部分描述不瞭解,可以直接檢視原始碼即可。
測試
首先隨便生成一個apk(API、混淆相關已經按照上述引入),安裝到手機或者模擬器上。
然後,copy出mapping.txt檔案,設定applymapping
,修改程式碼,再次打包,生成new.apk。
兩次的apk,可以通過命令列指令去生成patch檔案。
如果你下載本例,命令需要在[該目錄]下執行。
最終會在output資料夾中生成產物:
我們直接將patch_signed.apk push到sdcard,點選loadpatch,一定要觀察命令列是否成功。
本例修改了title。
點選loadPatch,觀察log,如果成功,應用預設為重啟,然後再次啟動即可達到修復效果。
到這裡命令列的方式就介紹完了,和Andfix的接入的方式基本上是一樣的。
值得注意的是:該例僅展示了基本的接入,對於tinker的各種配置資訊,還是需要去讀tinker的文件(如果你確定要使用)tinker-wiki。
(2)gradle接入
gradle接入的方式應該算是主流的方式,所以tinker也直接給出了例子,單獨將該tinker-sample-android以project方式引入即可。
引入之後,可以檢視其接入API的方式,以及相關配置。
在你每次build時,會在build/bakApk
下生成本地打包的apk,R檔案,以及mapping檔案。
如果你需要生成patch檔案,可以通過:
./gradlew tinkerPatchRelease
生成。
生成目錄為:build/outputs/tinkerPatch
需要注意的是,需要在app/build.gradle中設定相比較的apk(即old.apk,本次為new.apk),
ext {
tinkerEnabled = true
//old apk file to build patch apk
tinkerOldApkPath = "${bakPath}/old.apk"
//proguard mapping file to build patch apk
tinkerApplyMappingPath = "${bakPath}/old-mapping.txt"
}
提供的例子,基本上展示了tinker的自定義擴充套件的方式,具體還可以參考:
所以,如果你使用命令列方式接入,也不要忘了學習下其支援哪些擴充套件。
三、Application是如何編譯時生成的
從註釋和命名上看:
provided('com.tencent.tinker:tinker-android-anno:1.7.7')
明顯是該庫,其結構如下:
典型的編譯時註解的專案,原始碼見tinker-android-anno。
入口為com.tencent.tinker.anno.AnnotationProcessor
,可以在該services/javax.annotation.processing.Processor
檔案中找到處理類全路徑。
再次建議,如果你不瞭解,簡單閱讀下Android 如何編寫基於編譯時註解的專案該文。
直接看AnnotationProcessor的process
方法:
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
processDefaultLifeCycle(roundEnv.getElementsAnnotatedWith(DefaultLifeCycle.class));
return true;
}
直接呼叫了processDefaultLifeCycle:
private void processDefaultLifeCycle(Set<? extends Element> elements) {
for (Element e : elements) {
DefaultLifeCycle ca = e.getAnnotation(DefaultLifeCycle.class);
String lifeCycleClassName = ((TypeElement) e).getQualifiedName().toString();
String lifeCyclePackageName = lifeCycleClassName.substring(0, lifeCycleClassName.lastIndexOf('.'));
lifeCycleClassName = lifeCycleClassName.substring(lifeCycleClassName.lastIndexOf('.') + 1);
String applicationClassName = ca.application();
if (applicationClassName.startsWith(".")) {
applicationClassName = lifeCyclePackageName + applicationClassName;
}
String applicationPackageName = applicationClassName.substring(0, applicationClassName.lastIndexOf('.'));
applicationClassName = applicationClassName.substring(applicationClassName.lastIndexOf('.') + 1);
String loaderClassName = ca.loaderClass();
if (loaderClassName.startsWith(".")) {
loaderClassName = lifeCyclePackageName + loaderClassName;
}
final InputStream is = AnnotationProcessor.class.getResourceAsStream(APPLICATION_TEMPLATE_PATH);
final Scanner scanner = new Scanner(is);
final String template = scanner.useDelimiter("\\A").next();
final String fileContent = template
.replaceAll("%PACKAGE%", applicationPackageName)
.replaceAll("%APPLICATION%", applicationClassName)
.replaceAll("%APPLICATION_LIFE_CYCLE%", lifeCyclePackageName + "." + lifeCycleClassName)
.replaceAll("%TINKER_FLAGS%", "" + ca.flags())
.replaceAll("%TINKER_LOADER_CLASS%", "" + loaderClassName)
.replaceAll("%TINKER_LOAD_VERIFY_FLAG%", "" + ca.loadVerifyFlag());
JavaFileObject fileObject = processingEnv.getFiler().createSourceFile(applicationPackageName + "." + applicationClassName);
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Creating " + fileObject.toUri());
Writer writer = fileObject.openWriter();
PrintWriter pw = new PrintWriter(writer);
pw.print(fileContent);
pw.flush();
writer.close();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
程式碼比較簡單,可以分三部分理解:
- 步驟1:首先找到被DefaultLifeCycle標識的Element(為類物件TypeElement),得到該物件的包名,類名等資訊,然後通過該物件,拿到
@DefaultLifeCycle
物件,獲取該註解中宣告屬性的值。 - 步驟2:讀取一個模板檔案,讀取為字串,將各個佔位符通過步驟1中的值替代。
- 步驟3:通過JavaFileObject將替換完成的字串寫檔案,其實就是本例中的Application物件。
我們看一眼模板檔案:
package %PACKAGE%;
import com.tencent.tinker.loader.app.TinkerApplication;
/**
*
* Generated application for tinker life cycle
*
*/
public class %APPLICATION% extends TinkerApplication {
public %APPLICATION%() {
super(%TINKER_FLAGS%, "%APPLICATION_LIFE_CYCLE%", "%TINKER_LOADER_CLASS%", %TINKER_LOAD_VERIFY_FLAG%);
}
}
對應我們的SimpleTinkerInApplicationLike
,
@DefaultLifeCycle(application = ".SimpleTinkerInApplication",
flags = ShareConstants.TINKER_ENABLE_ALL,
loadVerifyFlag = false)
public class SimpleTinkerInApplicationLike extends ApplicationLike {}
主要就幾個佔位符:
- 包名,如果application屬性值以點開始,則同包;否則則擷取
- 類名,application屬性值中的類名
- %TINKER_FLAGS%對應flags
- %APPLICATION_LIFE_CYCLE%,編寫的ApplicationLike的全路徑
- “%TINKER_LOADER_CLASS%”,這個值我們沒有設定,實際上對應
@DefaultLifeCycle
的loaderClass屬性,預設值為com.tencent.tinker.loader.TinkerLoader
- %TINKER_LOAD_VERIFY_FLAG%對應loadVerifyFlag
於是最終生成的程式碼為:
/**
*
* Generated application for tinker life cycle
*
*/
public class SimpleTinkerInApplication extends TinkerApplication {
public SimpleTinkerInApplication() {
super(7, "com.zhy.tinkersimplein.SimpleTinkerInApplicationLike", "com.tencent.tinker.loader.TinkerLoader", false);
}
}
tinker這麼做的目的,文件上是這麼說的:
為了減少錯誤的出現,推薦使用Annotation生成Application類。
這樣大致瞭解了Application是如何生成的。
接下來我們大致看一下tinker的原理。
四、原理
來源於:https://github.com/Tencent/tinker
tinker貼了一張大致的原理圖。
可以看出:
tinker將old.apk和new.apk做了diff,拿到patch.dex,然後將patch.dex與本機中apk的classes.dex做了合併,生成新的classes.dex,執行時通過反射將合併後的dex檔案放置在載入的dexElements陣列的前面。
執行時替代的原理,其實和Qzone的方案差不多,都是去反射修改dexElements。
兩者的差異是:Qzone是直接將patch.dex插到陣列的前面;而tinker是將patch.dex與app中的classes.dex合併後的全量dex插在陣列的前面。
tinker這麼做的目的還是因為Qzone方案中提到的CLASS_ISPREVERIFIED
的解決方案存在問題;而tinker相當於換個思路解決了該問題。
接下來我們就從程式碼中去驗證該原理。
本片文章原始碼分析的兩條線:
- 應用啟動時,從預設目錄載入合併後的classes.dex
- patch下發後,合成classes.dex至目標目錄
五、原始碼分析
(1)載入patch
載入的程式碼實際上在生成的Application中呼叫的,其父類為TinkerApplication,在其attachBaseContext中輾轉會呼叫到loadTinker()方法,在該方法內部,反射呼叫了TinkerLoader的tryLoad方法。
@Override
public Intent tryLoad(TinkerApplication app, int tinkerFlag, boolean tinkerLoadVerifyFlag) {
Intent resultIntent = new Intent();
long begin = SystemClock.elapsedRealtime();
tryLoadPatchFilesInternal(app, tinkerFlag, tinkerLoadVerifyFlag, resultIntent);
long cost = SystemClock.elapsedRealtime() - begin;
ShareIntentUtil.setIntentPatchCostTime(resultIntent, cost);
return resultIntent;
}
tryLoadPatchFilesInternal中會呼叫到loadTinkerJars
方法:
private void tryLoadPatchFilesInternal(TinkerApplication app, int tinkerFlag, boolean tinkerLoadVerifyFlag, Intent resultIntent) {
if (isEnabledForDex) {
boolean dexCheck = TinkerDexLoader.checkComplete(patchVersionDirectory, securityCheck, resultIntent);
if (!dexCheck) {
Log.w(TAG, "tryLoadPatchFiles:dex check fail");
return;
}
}
if (isEnabledForDex) {
boolean loadTinkerJars = TinkerDexLoader.loadTinkerJars(app, tinkerLoadVerifyFlag, patchVersionDirectory, resultIntent, isSystemOTA);
if (!loadTinkerJars) {
Log.w(TAG, "tryLoadPatchFiles:onPatchLoadDexesFail");
return;
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
TinkerDexLoader.checkComplete主要是用於檢查下發的meta檔案中記錄的dex資訊(meta檔案,可以檢視生成patch的產物,在assets/dex-meta.txt),檢查meta檔案中記錄的dex檔案資訊對應的dex檔案是否存在,並把值存在TinkerDexLoader的靜態變數dexList中。
TinkerDexLoader.loadTinkerJars傳入四個引數,分別為application,tinkerLoadVerifyFlag(註解上宣告的值,傳入為false),patchVersionDirectory當前version的patch資料夾,intent,當前patch是否僅適用於art。
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static boolean loadTinkerJars(Application application, boolean tinkerLoadVerifyFlag,
String directory, Intent intentResult, boolean isSystemOTA) {
PathClassLoader classLoader = (PathClassLoader) TinkerDexLoader.class.getClassLoader();
String dexPath = directory + "/" + DEX_PATH + "/";
File optimizeDir = new File(directory + "/" + DEX_OPTIMIZE_PATH);
ArrayList<File> legalFiles = new ArrayList<>();
final boolean isArtPlatForm = ShareTinkerInternals.isVmArt();
for (ShareDexDiffPatchInfo info : dexList) {
if (isJustArtSupportDex(info)) {
continue;
}
String path = dexPath + info.realName;
File file = new File(path);
legalFiles.add(file);
}
if (isSystemOTA) {
parallelOTAResult = true;
parallelOTAThrowable = null;
Log.w(TAG, "systemOTA, try parallel oat dexes!!!!!");
TinkerParallelDexOptimizer.optimizeAll(
legalFiles, optimizeDir,
new TinkerParallelDexOptimizer.ResultCallback() {
}
);
SystemClassLoaderAdder.installDexes(application, classLoader, optimizeDir, legalFiles);
return true;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
找出僅支援art的dex,且當前patch是否僅適用於art時,並行去loadDex。
關鍵是最後的installDexes:
@SuppressLint("NewApi")
public static void installDexes(Application application, PathClassLoader loader, File dexOptDir, List<File> files)
throws Throwable {
if (!files.isEmpty()) {
ClassLoader classLoader = loader;
if (Build.VERSION.SDK_INT >= 24) {
classLoader = AndroidNClassLoader.inject(loader, application);
}
if (Build.VERSION.SDK_INT >= 23) {
V23.install(classLoader, files, dexOptDir);
} else if (Build.VERSION.SDK_INT >= 19) {
V19.install(classLoader, files, dexOptDir);
} else if (Build.VERSION.SDK_INT >= 14) {
V14.install(classLoader, files, dexOptDir);
} else {
V4.install(classLoader, files, dexOptDir);
}
sPatchDexCount = files.size();
Log.i(TAG, "after loaded classloader: " + classLoader + ", dex size:" + sPatchDexCount);
if (!checkDexInstall(classLoader)) {
SystemClassLoaderAdder.uninstallPatchDex(classLoader);
throw new TinkerRuntimeException(ShareConstants.CHECK_DEX_INSTALL_FAIL);
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
這裡實際上就是根據不同的系統版本,去反射處理dexElements。
我們看一下V19的實現(主要我看了下本機只有個22的原始碼~):
private static final class V19 {
private static void install(ClassLoader loader, List<File> additionalClassPathEntries,
File optimizedDirectory)
throws IllegalArgumentException, IllegalAccessException,
NoSuchFieldException, InvocationTargetException, NoSuchMethodException, IOException {
Field pathListField = ShareReflectUtil.findField(loader, "pathList");
Object dexPathList = pathListField.get(loader);
ArrayList<IOException> suppressedExceptions = new ArrayList<IOException>();
ShareReflectUtil.expandFieldArray(dexPathList, "dexElements", makeDexElements(dexPathList,
new ArrayList<File>(additionalClassPathEntries), optimizedDirectory,
suppressedExceptions));
if (suppressedExceptions.size() > 0) {
for (IOException e : suppressedExceptions) {
Log.w(TAG, "Exception in makeDexElement", e);
throw e;
}
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 找到PathClassLoader(BaseDexClassLoader)物件中的pathList物件
- 根據pathList物件找到其中的makeDexElements方法,傳入patch相關的對應的實參,返回Element[]物件
- 拿到pathList物件中原本的dexElements方法
- 步驟2與步驟3中的Element[]陣列進行合併,將patch相關的dex放在陣列的前面
- 最後將合併後的陣列,設定給pathList
這裡其實和Qzone的提出的方案基本是一致的。如果你以前未了解過Qzone的方案,可以參考此文:
(2)合成patch
這裡的入口為:
TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(),
Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed.apk")
上述程式碼會呼叫DefaultPatchListener中的onPatchReceived方法:
# DefaultPatchListener
@Override
public int onPatchReceived(String path) {
int returnCode = patchCheck(path);
if (returnCode == ShareConstants.ERROR_PATCH_OK) {
TinkerPatchService.runPatchService(context, path);
} else {
Tinker.with(context).getLoadReporter().onLoadPatchListenerReceiveFail(new File(path), returnCode);
}
return returnCode;
}
首先對tinker的相關配置(isEnable)以及patch的合法性進行檢測,如果合法,則呼叫TinkerPatchService.runPatchService(context, path);
。
public static void runPatchService(Context context, String path) {
try {
Intent intent = new Intent(context, TinkerPatchService.class);
intent.putExtra(PATCH_PATH_EXTRA, path);
intent.putExtra(RESULT_CLASS_EXTRA, resultServiceClass.getName());
context.startService(intent);
} catch (Throwable throwable) {
TinkerLog.e(TAG, "start patch service fail, exception:" + throwable);
}
}
TinkerPatchService是IntentService的子類,這裡通過intent設定了兩個引數,一個是patch的路徑,一個是resultServiceClass,該值是呼叫Tinker.install的時候設定的,預設為DefaultTinkerResultService.class
。由於是IntentService,直接看onHandleIntent即可,如果你對IntentService陌生,可以檢視此文:Android
IntentService完全解析 當Service遇到Handler
。
@Override
protected void onHandleIntent(Intent intent) {
final Context context = getApplicationContext();
Tinker tinker = Tinker.with(context);
String path = getPatchPathExtra(intent);
File patchFile = new File(path);
boolean result;
increasingPriority();
PatchResult patchResult = new PatchResult();
result = upgradePatchProcessor.tryPatch(context, path, patchResult);
patchResult.isSuccess = result;
patchResult.rawPatchFilePath = path;
patchResult.costTime = cost;
patchResult.e = e;
AbstractResultService.runResultService(context, patchResult, getPatchResultExtra(intent));
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
比較清晰,主要關注upgradePatchProcessor.tryPatch方法,呼叫的是UpgradePatch.tryPatch。ps:這裡有個有意思的地方increasingPriority(),其內部實現為:
private void increasingPriority() {
TinkerLog.i(TAG, "try to increase patch process priority");
try {
Notification notification = new Notification();
if (Build.VERSION.SDK_INT < 18) {
startForeground(notificationId, notification);
} else {
startForeground(notificationId, notification);
startService(new Intent(this, InnerService.class));
}
} catch (Throwable e) {
TinkerLog.i(TAG, "try to increase patch process priority error:" + e);
}
}
如果你對“保活”這個話題比較關注,那麼對這段程式碼一定不陌生,主要是利用系統的一個漏洞來啟動一個前臺Service。如果有興趣,可以參考此文:關於 Android 程式保活,你所需要知道的一切。
下面繼續回到tryPatch方法:
# UpgradePatch
@Override
public boolean tryPatch(Context context, String tempPatchPath, PatchResult patchResult) {
Tinker manager = Tinker.with(context);
final File patchFile = new File(tempPatchPath);
SharePatchInfo oldInfo = manager.getTinkerLoadResultIfPresent().patchInfo;
String patchMd5 = SharePatchFileUtil.getMD5(patchFile);
patchResult.patchVersion = patchMd5;
SharePatchInfo newInfo;
if (oldInfo != null) {
newInfo = new SharePatchInfo(oldInfo.oldVersion, patchMd5, Build.FINGERPRINT);
} else {
newInfo = new SharePatchInfo("", patchMd5, Build.FINGERPRINT);
}
final String patchDirectory = manager.getPatchDirectory().getAbsolutePath();
final String patchName = SharePatchFileUtil.getPatchVersionDirectory(patchMd5);
final String patchVersionDirectory = patchDirectory + "/" + patchName;
File destPatchFile = new File(patchVersionDirectory + "/" + SharePatchFileUtil.getPatchVersionFile(patchMd5));
if (!patchMd5.equals(SharePatchFileUtil.getMD5(destPatchFile))) {
SharePatchFileUtil.copyFileUsingStream(patchFile, destPatchFile);
}
if (!DexDiffPatchInternal.tryRecoverDexFiles(manager, signatureCheck, context, patchVersionDirectory,
destPatchFile)) {
TinkerLog.e(TAG, "UpgradePatch tryPatch:new patch recover, try patch dex failed");
return false;
}
return true;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
拷貝patch檔案拷貝至私有目錄,然後呼叫DexDiffPatchInternal.tryRecoverDexFiles
:
protected static boolean tryRecoverDexFiles(Tinker manager, ShareSecurityCheck checker, Context context,
String patchVersionDirectory, File patchFile) {
String dexMeta = checker.getMetaContentMap().get(DEX_META_FILE);
boolean result = patchDexExtractViaDexDiff(context, patchVersionDirectory, dexMeta, patchFile);
return result;
}
直接看patchDexExtractViaDexDiff
private static boolean patchDexExtractViaDexDiff(Context context, String patchVersionDirectory, String meta, final File patchFile) {
String dir = patchVersionDirectory + "/" + DEX_PATH + "/";
if (!extractDexDiffInternals(context, dir, meta, patchFile, TYPE_DEX)) {
TinkerLog.w(TAG, "patch recover, extractDiffInternals fail");
return false;
}
final Tinker manager = Tinker.with(context);
File dexFiles = new File(dir);
File[] files = dexFiles.listFiles();
...files遍歷執行:DexFile.loadDex
return true;
}
核心程式碼主要在extractDexDiffInternals中:
private static boolean extractDexDiffInternals(Context context, String dir, String meta, File patchFile, int type) {
ArrayList<ShareDexDiffPatchInfo> patchList = new ArrayList<>();
ShareDexDiffPatchInfo.parseDexDiffPatchInfo(meta, patchList);
File directory = new File(dir);
Tinker manager = Tinker.with(context);
ZipFile apk = null;
ZipFile patch = null;
ApplicationInfo applicationInfo = context.getApplicationInfo();
String apkPath = applicationInfo.sourceDir;
apk = new ZipFile(apkPath);
patch = new ZipFile(patchFile);
for (ShareDexDiffPatchInfo info : patchList) {
final String infoPath = info.path;
String patchRealPath;
if (infoPath.equals("")) {
patchRealPath = info.rawName;
} else {
patchRealPath = info.path + "/" + info.rawName;
}
File extractedFile = new File(dir + info.realName);
ZipEntry patchFileEntry = patch.getEntry(patchRealPath);
ZipEntry rawApkFileEntry = apk.getEntry(patchRealPath);
patchDexFile(apk, patch, rawApkFileEntry, patchFileEntry, info, extractedFile);
}
return true;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
這裡的程式碼比較關鍵了,可以看出首先解析了meta裡面的資訊,meta中包含了patch中每個dex的相關資料。然後通過Application拿到sourceDir,其實就是本機apk的路徑以及patch檔案;根據mate中的資訊開始遍歷,其實就是取出對應的dex檔案,最後通過patchDexFile對兩個dex檔案做合併。
private static void patchDexFile(
ZipFile baseApk, ZipFile patchPkg, ZipEntry oldDexEntry, ZipEntry patchFileEntry,
ShareDexDiffPatchInfo patchInfo, File patchedDexFile) throws IOException {
InputStream oldDexStream = null;
InputStream patchFileStream = null;
oldDexStream = new BufferedInputStream(baseApk.getInputStream(oldDexEntry));
patchFileStream = (patchFileEntry != null ? new BufferedInputStream(patchPkg.getInputStream(patchFileEntry)) : null);
new DexPatchApplier(oldDexStream, patchFileStream).executeAndSaveTo(patchedDexFile);
}
通過ZipFile拿到其內部檔案的InputStream,其實就是讀取本地apk對應的dex檔案,以及patch中對應dex檔案,對二者的通過executeAndSaveTo方法進行合併至patchedDexFile,即patch的目標私有目錄。
至於合併演算法,這裡其實才是tinker比較核心的地方,這個演算法跟dex檔案格式緊密關聯,如果有機會,然後我又能看懂的話,後面會單獨寫篇部落格介紹。此外dodola已經有篇部落格進行了介紹:
感興趣的可以閱讀下。
好了,到此我們就大致瞭解了tinker熱修復的原理~~
測試demo地址:
當然這裡只分析了程式碼了熱修復,後續考慮分析資源以及So的熱修、核心的diff演算法、以及gradle外掛等相關知識~