更新
这适用于Dalvik和ART:新的DexClassLoader(jarredDex.getAbsolutePath(),context.getDir(“outdex”,Context.MODE_PRIVATE).getAbsolutePath(),null,context.getClassLoader());其中jarredDex是一个带有classes.dex的jar文件. Jar可以通过运行dx –dex –output = filename.jar你的/ classes / dir来获得.
原始答案
我从this article开始使用代码示例.但ART使用PathClassLoader而不是Dalvik的DexClassLoader.此代码在Android 6的模拟器和Android 5.1的小米上进行了测试,效果很好:
// Before the secondary dex file can be processed by the DexClassLoader,
// it has to be first copied from asset resource to a storage location.
File dexInternalStoragePath = new File(getDir("dex", Context.MODE_PRIVATE), SECONDARY_DEX_NAME);
try (BufferedInputStream bis = new BufferedInputStream(getAssets().open(SECONDARY_DEX_NAME));
OutputStream dexWriter = new BufferedOutputStream(new FileOutputStream(dexInternalStoragePath))) {
byte[] buf = new byte[BUF_SIZE];
int len;
while((len = bis.read(buf, 0, BUF_SIZE)) > 0) {
dexWriter.write(buf, 0, len);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
PathClassLoader loader = new PathClassLoader(dexInternalStoragePath.getAbsolutePath(), getClassLoader());
Class> toasterClass = loader.loadClass("my.package.ToasterImpl");
Toaster toaster = (Toaster) toasterClass.newInstance();
toaster.show(this, "Success!");
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}