MultiDex的具體實(shí)現(xiàn)過(guò)程
一、代碼示例
1氏仗、Gradle修改
修改Gradle的配置吉捶,支持multidex:
android {
compileSdkVersion 21
buildToolsVersion "21.1.0"
defaultConfig {
...
minSdkVersion 14
targetSdkVersion 21
...
// Enabling multidex support.
multiDexEnabled true
}
...
}
dependencies {
compile 'com.android.support:multidex:1.0.0'
}
2、manifest修改
在manifest文件中廓鞠,在application標(biāo)簽下添加MultidexApplication Class的引用
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.multidex.myapplication">
<application
...
android:name="android.support.multidex.MultiDexApplication">
...
</application>
</manifest>
二帚稠、實(shí)現(xiàn)源碼
1、MultiDexApplication
public class MultiDexApplication extends Application {
public MultiDexApplication() {
}
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
使用 MultiDexApplication的原因就是它重寫(xiě)了Application床佳,主要是可以將其他dex文件注入到系統(tǒng)的ClassLoader
2、MultiDex
MultiDex.install榄审,這個(gè)方法涵蓋了MultiDex安裝的整個(gè)流程:
publicstaticvoidinstall(Context context){
Log.i(TAG, "install");
// 檢查當(dāng)前系統(tǒng)是否支持multidex
if (IS_VM_MULTIDEX_CAPABLE) {
Log.i(TAG, "VM has multidex support, MultiDex support library is disabled.");
try {
clearOldDexDir(context);
} catch (Throwable t) {
Log.w(TAG, "Something went wrong when trying to clear old MultiDex extraction, "
+ "continuing without cleaning.", t);
}
return;
}
// MultiDex最低只支持到1.6
if (Build.VERSION.SDK_INT < MIN_SDK_VERSION) {
throw new RuntimeException("Multi dex installation failed. SDK " + Build.VERSION.SDK_INT
+ " is unsupported. Min SDK version is " + MIN_SDK_VERSION + ".");
}
try {
ApplicationInfo applicationInfo = getApplicationInfo(context);
if (applicationInfo == null) {
// Looks like running on a test Context, so just return without patching.
return;
}
synchronized (installedApk) {
// sourceDir對(duì)應(yīng)于/data/app/<package-name>.apk
String apkPath = applicationInfo.sourceDir;
// 若給定apk已經(jīng)install過(guò)砌们,直接退出
if (installedApk.contains(apkPath)) {
return;
}
installedApk.add(apkPath);
// MultiDex 最高只支持到20(Android 4.4W),更高的版本不能保證正常工作
if (Build.VERSION.SDK_INT > MAX_SUPPORTED_SDK_VERSION) {
Log.w(TAG, "MultiDex is not guaranteed to work in SDK version "
+ Build.VERSION.SDK_INT + ": SDK version higher than "
+ MAX_SUPPORTED_SDK_VERSION + " should be backed by "
+ "runtime with built-in multidex capabilty but it's not the "
+ "case here: java.vm.version=\""
+ System.getProperty("java.vm.version") + "\"");
}
// 得到classLoader搁进,它就是PathClassLoader是BaseDexClassLoaderd的子類浪感,
// MultiDex主要通過(guò)修改pathList字段來(lái)添加更多的dex
// 后面就可以從這個(gè)PathClassLoader中拿到DexPathList中的Element數(shù)組
// 這個(gè)數(shù)組里面就包括由系統(tǒng)加載第一個(gè)dex包
ClassLoader loader;
try {
loader = context.getClassLoader();
} catch (RuntimeException e) {
/* Ignore those exceptions so that we don't break tests relying on Context like
* a android.test.mock.MockContext or a android.content.ContextWrapper with a
* null base Context.
*/
Log.w(TAG, "Failure while trying to obtain Context class loader. " +
"Must be running in test mode. Skip patching.", e);
return;
}
if (loader == null) {
// Note, the context class loader is null when running Robolectric tests.
Log.e(TAG,
"Context class loader is null. Must be running in test mode. "
+ "Skip patching.");
return;
}
// MultiDex的二級(jí)dex文件將存放在 /data/data/<package-name>/secondary-dexes 下
File dexDir = new File(context.getFilesDir(), SECONDARY_FOLDER_NAME);
// 從apk中查找并解壓二級(jí)dex文件到/data/data/<package-name>/secondary-dexes
List<File> files = MultiDexExtractor.load(context, applicationInfo, dexDir, false);
// 檢查dex壓縮文件的完整性
if (checkValidZipFiles(files)) {
// 開(kāi)始安裝dex
installSecondaryDexes(loader, dexDir, files);
} else {
Log.w(TAG, "Files were not valid zip files. Forcing a reload.");
/**
第一次檢查失敗,MultiDex會(huì)盡責(zé)的再檢查一次
若第一次校驗(yàn)失敱省(dex文件損壞等)影兽,
MultiDex會(huì)重新調(diào)用MultiDexExtractor.load方法重查找加載二級(jí)dex文件列表,
值得注意的是此時(shí)forceReload的值為true莱革,會(huì)強(qiáng)制重新從apk中解壓dex文件
*/
files = MultiDexExtractor.load(context, applicationInfo, dexDir, true);
if (checkValidZipFiles(files)) {
// 開(kāi)始安裝dex
installSecondaryDexes(loader, dexDir, files);
} else {
// Second time didn't work, give up
throw new RuntimeException("Zip files were not valid.");
}
}
}
} catch (Exception e) {
Log.e(TAG, "Multidex installation failure", e);
throw new RuntimeException("Multi dex installation failed (" + e.getMessage() + ").");
}
Log.i(TAG, "install done");
}
1峻堰、檢查虛擬機(jī)版本
跟虛擬機(jī)版本判斷是否需要MultiDex;
在ART虛擬機(jī)中(部分4.4機(jī)器及5.0以上的機(jī)器)讹开,采用了Ahead-of-time(AOT)compilation技術(shù),系統(tǒng)在apk的安裝過(guò)程中捐名,會(huì)使用自帶的dex2oat工具對(duì)apk中可用的dex文件進(jìn)行編譯旦万,并生成一個(gè)可在本地機(jī)器上運(yùn)行的odex(optimized dex)文件,這樣做會(huì)提高應(yīng)用的啟動(dòng)速度镶蹋。(但是安裝速度降低了)
若不需要使用MultiDex成艘,將使用clearOldDexDir清除/data/data/pkgName/code-cache/secondary-dexes目錄下下所有文件
2、獲取安裝路徑
根據(jù)applicationInfo.sourceDir的值獲取安裝的apk路徑贺归;安裝完成的apk路徑為 /data/app/.apk
3淆两、安裝檢測(cè)
檢查apk是否執(zhí)行過(guò)MultiDex.install,若已經(jīng)安裝直接退出
4拂酣、獲取二級(jí)dex列表
MultiDexExtractor.load獲取apk中二級(jí)dex列表
5琼腔、校驗(yàn)dex壓縮包的完整性
6、開(kāi)始dex的安裝
installSecondaryDexes 安裝dex
// loader對(duì)應(yīng)的就是PathClassLoader
// dexDir是dex的存放目錄
// files對(duì)應(yīng)的就是dex文件
private static void installSecondaryDexes(ClassLoader loader, File dexDir, List<File> files) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, InvocationTargetException, NoSuchMethodException, IOException {
if(!files.isEmpty()) {
if(VERSION.SDK_INT >= 19) {
MultiDex.V19.install(loader, files, dexDir);
} else if(VERSION.SDK_INT >= 14) {
MultiDex.V14.install(loader, files, dexDir);
} else {
MultiDex.V4.install(loader, files);
}
}
}
由于SDK版本不同踱葛,ClassLoader中的實(shí)現(xiàn)存在差異丹莲,所以使用了三個(gè)分支去執(zhí)行dex的安裝。這里我們選擇MultiDex.V14.install進(jìn)行分析尸诽,其他兩個(gè)大同小異:
V14.install
private static void install(ClassLoader loader, List<File> additionalClassPathEntries, File optimizedDirectory) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, InvocationTargetException, NoSuchMethodException {
// 這個(gè)方法就是使用反射來(lái)得到loader的pathList字段
Field pathListField = MultiDex.findField(loader, "pathList");
// 得到loader的pathList字段后甥材,我們就可以得到這個(gè)字段的值,也就是DexPathList對(duì)象
Object dexPathList = pathListField.get(loader);
// 這個(gè)方法就是將其他的dex文件Element數(shù)組和第一個(gè)dex的Element數(shù)組合并
// makeDexElements方法就是用來(lái)得到其他dex的Elements數(shù)組
MultiDex.expandFieldArray(dexPathList, "dexElements", makeDexElements(dexPathList, new ArrayList(additionalClassPathEntries), optimizedDirectory));
}
MultiDex在安裝開(kāi)始時(shí)性含,會(huì)先通過(guò)反射調(diào)用 BaseDexClassLoader 里DexPathList類型的pathList字段洲赵,接著通過(guò)pathList調(diào)用 DexPathList 的makeDexElements方法,將上面解壓得到的additionalClassPathEntries(二級(jí)dex文件列表)封裝成Element數(shù)組商蕴。
需要注意的是叠萍,makeDexElements最終會(huì)去進(jìn)行dex2opt操作,這是一個(gè)比較耗時(shí)的過(guò)程绪商,如果全部放在main線程去處理的話苛谷,比較影響用戶體驗(yàn),甚至可能引起ANR格郁。
7腹殿、合并數(shù)組
調(diào)用 MultiDex.expandFieldArray 合并dex 數(shù)組
// instance對(duì)應(yīng)的就是pathList對(duì)象
// fieldName 對(duì)應(yīng)的就是字段名,我們要得到的就是pathList對(duì)象里面的dexElements數(shù)組
// extraElements對(duì)應(yīng)的就是其他dex對(duì)應(yīng)的Element數(shù)組
private static void expandFieldArray(Object instance, String fieldName, Object[] extraElements) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
// 得到Element數(shù)組字段
Field jlrField = findField(instance, fieldName);
// 得到pathList對(duì)象里面的dexElements數(shù)組
Object[] original = (Object[])((Object[])jlrField.get(instance));
// 創(chuàng)建一個(gè)新的數(shù)組用來(lái)存放合并之后的結(jié)果
Object[] combined = (Object[])((Object[])Array.newInstance(original.getClass().getComponentType(), original.length + extraElements.length));
// 將第一個(gè)dex的Elements數(shù)組復(fù)制到創(chuàng)建的數(shù)組中去
System.arraycopy(original, 0, combined, 0, original.length);
// 將其他dex的Elements數(shù)組復(fù)制到創(chuàng)建的數(shù)組中去
System.arraycopy(extraElements, 0, combined, original.length, extraElements.length);
// 將得到的這個(gè)合并的新數(shù)組的值設(shè)置到pathList對(duì)象的Element數(shù)組字段上
jlrField.set(instance, combined);
}
expandFieldArray同樣是通過(guò)反射調(diào)用例书,找到pathList中的dexElements字段锣尉,并將上一步生成的封裝了二級(jí)dex的Element數(shù)組添加到dexElements之后,完成整個(gè)安裝流程
8决采、其他涉及的方法
MultiDexExtractor.load(……獲取apk中可用的二級(jí)dex列表
/**
MultiDexExtractor.load會(huì)先判斷是否需要從apk中解壓dex文件自沧,主要判斷依據(jù)是:上次保存的apk(zip文件)的CRC校驗(yàn)碼和last modify日期與dex的總數(shù)量是否與當(dāng)前apk相同。此外树瞭,forceReload也會(huì)決定是否需要重新解壓
*/
private static List<File> load(Context context, ApplicationInfo applicationInfo, File dexDir,booleanforceReload)throwsIOException{
Log.i("MultiDex", "MultiDexExtractor.load(" + applicationInfo.sourceDir + ", " + forceReload + ")");
File sourceApk = new File(applicationInfo.sourceDir);
long currentCrc = getZipCrc(sourceApk);
List files;
if(!forceReload && !isModified(context, sourceApk, currentCrc)) {
try {
files = loadExistingExtractions(context, sourceApk, dexDir);
} catch (IOException var9) {
Log.w("MultiDex", "Failed to reload existing extracted secondary dex files, falling back to fresh extraction", var9);
files = performExtractions(sourceApk, dexDir);
putStoredApkInfo(context, getTimeStamp(sourceApk), currentCrc, files.size() + 1);
}
} else {
Log.i("MultiDex", "Detected that extraction must be performed.");
files = performExtractions(sourceApk, dexDir);
putStoredApkInfo(context, getTimeStamp(sourceApk), currentCrc, files.size() + 1);
}
Log.i("MultiDex", "load found " + files.size() + " secondary dex files");
return files;
}
解壓apk
private static List<File> performExtractions(File sourceApk, File dexDir)throwsIOException{
// extractedFilePrefix值為<package-name>.apk.classes
String extractedFilePrefix = sourceApk.getName() + ".classes";
prepareDexDir(dexDir, extractedFilePrefix);
ArrayList files = new ArrayList();
ZipFile apk = new ZipFile(sourceApk);
try {
int e = 2;
// 掃描apk內(nèi)所有classes2.dex拇厢、classes3.dex...文件
for(ZipEntry dexFile = apk.getEntry("classes" + e + ".dex"); dexFile != null; dexFile = apk.getEntry("classes" + e + ".dex")) {
// 解壓路徑為 /data/data/<package-name>/secondary-dexes/<package-name>.classes2.dex.zip 爱谁、/data/data/<package-name>/secondary-dexes/<package-name>.classes3.dex.zip ...
String fileName = extractedFilePrefix + e + ".zip";
File extractedFile = new File(dexDir, fileName);
files.add(extractedFile);
Log.i("MultiDex", "Extraction is needed for file " + extractedFile);
int numAttempts = 0;
boolean isExtractionSuccessful = false;
// 每個(gè)dex文件都會(huì)嘗試3次解壓
while(numAttempts < 3 && !isExtractionSuccessful) {
++numAttempts;
extract(apk, dexFile, extractedFile, extractedFilePrefix);
isExtractionSuccessful = verifyZipFile(extractedFile);
Log.i("MultiDex", "Extraction " + (isExtractionSuccessful?"success":"failed") + " - length " + extractedFile.getAbsolutePath() + ": " + extractedFile.length());
if(!isExtractionSuccessful) {
extractedFile.delete();
if(extractedFile.exists()) {
Log.w("MultiDex", "Failed to delete corrupted secondary dex \'" + extractedFile.getPath() + "\'");
}
}
}
if(!isExtractionSuccessful) {
throw new IOException("Could not create zip file " + extractedFile.getAbsolutePath() + " for secondary dex (" + e + ")");
}
++e;
}
} finally {
try {
apk.close();
} catch (IOException var16) {
Log.w("MultiDex", "Failed to close resource", var16);
}
}
return files;
}
解壓成功后,會(huì)保存本次解壓所使用的apk信息旺嬉,用于下次調(diào)用MultiDexExtractor.load時(shí)判斷是否需要重新解壓:
private static void putStoredApkInfo(Context context,longtimeStamp,longcrc,inttotalDexNumber){
SharedPreferences prefs = getMultiDexPreferences(context);
Editor edit = prefs.edit();
// apk最后修改時(shí)間戳
edit.putLong("timestamp", timeStamp);
// apk的CRC校驗(yàn)碼
edit.putLong("crc", crc);
// dex的總數(shù)量
edit.putInt("dex.number", totalDexNumber);
apply(edit);
}
如果apk未被修改管行,將會(huì)調(diào)用loadExistingExtractions方法,直接加載上一次解壓出來(lái)的文件
privatestaticList<File>loadExistingExtractions(Context context, File sourceApk, File dexDir)throwsIOException{
Log.i("MultiDex", "loading existing secondary dex files");
String extractedFilePrefix = sourceApk.getName() + ".classes";
int totalDexNumber = getMultiDexPreferences(context).getInt("dex.number", 1);
ArrayList files = new ArrayList(totalDexNumber);
for(int secondaryNumber = 2; secondaryNumber <= totalDexNumber; ++secondaryNumber) {
String fileName = extractedFilePrefix + secondaryNumber + ".zip";
File extractedFile = new File(dexDir, fileName);
if(!extractedFile.isFile()) {
throw new IOException("Missing extracted secondary dex file \'" + extractedFile.getPath() + "\'");
}
files.add(extractedFile);
if(!verifyZipFile(extractedFile)) {
Log.i("MultiDex", "Invalid zip file: " + extractedFile);
throw new IOException("Invalid ZIP file.");
}
}
return files;
}