上述方法中的本质是将可以分包的jar打包为一个apk文件,放在assets文件夹下,在应用初始化时加载此apk文件
下面是具体操作步骤:
1、将可以分到第二个包的jar文件利用ant合并合并为一个jar包,然后转换为dex文件,命名为classes.dex,添加为压缩文 件, 并命名为libs.apk
2、将libs.apk放入项目的assets文件夹下
3.将步骤1中的jar包从项目libs文件夹下删除,将合并后的jar包依照android.jar的方式引入项目
项目--右键--Build Path --Configure Build Path --- Libraries ---Add External JARs
4、在项目的Application中添加下面的方法
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
dexTool();
}
/**
* Copy the following code and call dexTool() after super.onCreate() in
* Application.onCreate()
*
* This method hacks the default PathClassLoader and load the secondary dex
* file as it's parent.
*/
@SuppressLint("NewApi")
private void dexTool() {
File dexDir = new File(getFilesDir(), "dlibs");
dexDir.mkdir();
File dexFile = new File(dexDir, "libs.apk");
File dexOpt = new File(dexDir, "opt");
dexOpt.mkdir();
try {
InputStream ins = getAssets().open("libs.apk");
if (dexFile.length() != ins.available()) {
FileOutputStream fos = new FileOutputStream(dexFile);
byte[] buf = new byte[4096];
int l;
while ((l = ins.read(buf)) != -1) {
fos.write(buf, 0, l);
}
fos.close();
}
ins.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
ClassLoader cl = getClassLoader();
ApplicationInfo ai = getApplicationInfo();
String nativeLibraryDir = null;
if (Build.VERSION.SDK_INT > 8) {
nativeLibraryDir = ai.nativeLibraryDir;
} else {
nativeLibraryDir = "/data/data/" + ai.packageName + "/lib/";
}
DexClassLoader dcl = new DexClassLoader(dexFile.getAbsolutePath(),
dexOpt.getAbsolutePath(), nativeLibraryDir, cl.getParent());
try {
Field f = ClassLoader.class.getDeclaredField("parent");
f.setAccessible(true);
f.set(cl, dcl);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
注:Application中的静态全局变量会比MutiDex的instal()方法优先加载,所以建议避免在Application类中使用引用classes2.dex文件的静态变量
到此,问题解决。