defaultConfig{
multiDexEnabled true
}
implementation 'com.android.support:multidex:1.0.3'
MultiDex.install(this);
com/alex/kotlin/jniapplication/MainActivity.class
com/alex/kotlin/jniapplication/MainActivity2.class
multiDexKeepFile file('multidex-config.txt')
public static void install(Context context) {
if (IS_VM_MULTIDEX_CAPABLE) {
} else if (VERSION.SDK_INT < 4) { //Multidex 最小支持版本SDK_INT 为 4
throw new RuntimeException("MultiDex installation failed. SDK " + VERSION.SDK_INT + " is unsupported. Min SDK version is " + 4 + ".");
} else {
try {
ApplicationInfo applicationInfo = getApplicationInfo(context); //获取程序的ApplicationInfo
//分别传入apk安装文件和apk的信息文件
doInstallation(context, new File(applicationInfo.sourceDir), new File(applicationInfo.dataDir), "secondary-dexes", "", true);
} catch (Exception var2) {}
}
}
private static void doInstallation(Context mainContext, File sourceApk, File dataDir, String secondaryFolderName, String prefsKeyPrefix, boolean reinstallOnPatchRecoverableException) {
synchronized(installedApk) {
if (!installedApk.contains(sourceApk)) { // 判读次APk是否被加载过,加载过会自动跳过
installedApk.add(sourceApk); // 静态集合保存被加载的apk
ClassLoader loader;
try {
loader = mainContext.getClassLoader(); //获取系统的ClassLoader实例
} catch (RuntimeException var25) {}
clearOldDexDir(mainContext); //清除旧的加载信息
//在dataDir文件夹下创建加载dex文件的缓存目录 code_cache/secondary-dexes
//如果dataDir创建失败会创建getFilesDir()为缓存目录
File dexDir = getDexDir(mainContext, dataDir, secondaryFolderName);
MultiDexExtractor extractor = new MultiDexExtractor(sourceApk, dexDir);
//创建MultiDexExtractor实例,保存源文件目录和缓存目录
try {
List files = extractor.load(mainContext, prefsKeyPrefix, false); //(1)加载dex文件
try {
installSecondaryDexes(loader, dexDir, files); //(2)安装dex文件
} catch (IOException var26) {
files = extractor.load(mainContext, prefsKeyPrefix, true); //出现异常会强制重新加载,参数true
installSecondaryDexes(loader, dexDir, files);
}
} finally {
try {
extractor.close();
} catch (IOException var23) {
closeException = var23;
}
}
}
}
总结:
List<? extends File> load(Context context, String prefsKeyPrefix, boolean forceReload) throws IOException {
List files;
// 判断是否强制重新加载 或 Dex文件是否有改变
if (!forceReload && !isModified(context, this.sourceApk, this.sourceCrc, prefsKeyPrefix)) {
try {
files = this.loadExistingExtractions(context, prefsKeyPrefix);//未强制和未改变的直接从缓存的dex中加载
} catch (IOException var6) {
files = this.performExtractions();
putStoredApkInfo(context, prefsKeyPrefix, getTimeStamp(this.sourceApk), this.sourceCrc, files);
}
} else {
files = this.performExtractions(); //强制重新加载
putStoredApkInfo(context, prefsKeyPrefix, getTimeStamp(this.sourceApk), this.sourceCrc, files); //缓存信息
}
return files;
}
总结:
如果没有强制重新加载、文件存在且没有变化则从缓存的dex中加载
未加载过的执行加载程序并缓存信息
performExtractions()
private List<MultiDexExtractor.ExtractedDex> performExtractions() throws IOException {
String extractedFilePrefix = this.sourceApk.getName() + ".classes”; //设置文件名前缀
this.clearDexDir();
List<MultiDexExtractor.ExtractedDex> files = new ArrayList();
ZipFile apk = new ZipFile(this.sourceApk); //将传入的APK文件转换为Zip压缩文件
try {
int secondaryNumber = 2; //排除主Dex从第二个dex中开始遍历加载
for(ZipEntry dexFile = apk.getEntry("classes" + secondaryNumber + ".dex"); dexFile != null; dexFile = apk.getEntry("classes" + secondaryNumber + ".dex")) { //循环获取apk文件夹下的dex文件
String fileName = extractedFilePrefix + secondaryNumber + ".zip”; //每个dex文件生成对应的zip文件
//对每个dex文件都创建一个文件extractedFile并保存到集合中
MultiDexExtractor.ExtractedDex extractedFile = new MultiDexExtractor.ExtractedDex(this.dexDir, fileName);
files.add(extractedFile);
int numAttempts = 0; //统计加载次数,默认加载3次,超过3次还不成功则加载失败
boolean isExtractionSuccessful = false; //标记是否加载成功
while(numAttempts < 3 && !isExtractionSuccessful) { //循环执行加载
++numAttempts;
extract(apk, dexFile, extractedFile, extractedFilePrefix); //真正执行加载的方法
try {
extractedFile.crc = getZipCrc(extractedFile); //加载成功
isExtractionSuccessful = true;
} catch (IOException var18) {
}
}
++secondaryNumber; //继续加载下一个dex文件
}
} finally {
}
return files;
}
上述代码执行逻辑:
将传入的APK文件转换为Zip压缩文件,则每个dex文件都是Zip下的子文件
排除主Dex从第二个dex中开始遍历加载,并根据secondaryNumber获取Zip下个每个dex文件,然后在code_cache/secondary-dexes目录下为每个dex创建zip文件
对每个dex文件都创建一个文件extractedFile并保存到集合中
执行extract()进行文件加载
extract():执行文件的写入,将apk中除了主dex之外的dex文件逐个读取写入到zip文件中
private static void extract(ZipFile apk, ZipEntry dexFile, File extractTo, String extractedFilePrefix) throws IOException, FileNotFoundException {
InputStream in = apk.getInputStream(dexFile); //从dexFile中获取字节流
ZipOutputStream out = null;
//在缓存文件夹目录中创建临时文件夹 tmp-***.zip
File tmp = File.createTempFile("tmp-" + extractedFilePrefix, ".zip", extractTo.getParentFile());
try {
out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(tmp))); //创建ZipOutputStream输出流
try {
ZipEntry classesDex = new ZipEntry("classes.dex");
classesDex.setTime(dexFile.getTime());
out.putNextEntry(classesDex); //设置Zip文件
byte[] buffer = new byte[16384]; //读取dexFile中的字节流写入临时文件tem中保存在缓存文件夹下
for(int length = in.read(buffer); length != -1; length = in.read(buffer)) {
out.write(buffer, 0, length); //将数据写入名为classes.dex的Zip文件
}
out.closeEntry();
} finally {
out.close();
}
} finally {
closeQuietly(in);
tmp.delete();
}
}
private static void installSecondaryDexes(ClassLoader loader, File dexDir, List<? extends File> files){
if (!files.isEmpty()) { //文件是否为null
if (VERSION.SDK_INT >= 19) {
MultiDex.V19.install(loader, files, dexDir); // 根据SDK不同执行不同的install逻辑,从缓存文件中加载
} else if (VERSION.SDK_INT >= 14) {
MultiDex.V14.install(loader, files);
} else {
MultiDex.V4.install(loader, files);
}
}
}
static void install(ClassLoader loader, List<? extends File> additionalClassPathEntries, File optimizedDirectory) {
Field pathListField = MultiDex.findField(loader, "pathList”); //反射调用ClassLoader的pathList
Object dexPathList = pathListField.get(loader);
ArrayList<IOException> suppressedExceptions = new ArrayList();
//将取出的zip文件包装成Element对象并扩招dexElements
MultiDex.expandFieldArray(dexPathList, "dexElements", makeDexElements(dexPathList, new ArrayList(additionalClassPathEntries), optimizedDirectory, suppressedExceptions));
}
private static Object[] makeDexElements(Object dexPathList, ArrayList<File> files, File optimizedDirectory, ArrayList<IOException> suppressedExceptions) {
//调用dexPathList中的makeDexElements方法传入文件集合,解析zip文件集合中的dex文件保存为Elements
Method makeDexElements = MultiDex.findMethod(dexPathList, "makeDexElements", ArrayList.class, File.class, ArrayList.class);
//执行方法
return (Object[])((Object[])makeDexElements.invoke(dexPathList, files, optimizedDirectory, suppressedExceptions));
}
上面主要是使用ClassLoader加载文件,关于ClassLoader不熟悉的点击Android热修复之路(一)——ClassLoader查看,上述代码的执行逻辑:
关于MutilDex的加载原理就到此结束了,简单来说就是将所有的dex都加载在Element数组中,然后扩展只ClassLoader的pathList中,在ClassLoader查找类时就可以找到了;