更新
这适用于的Dalvik和ART:new DexClassLoader(jarredDex.getAbsolutePath(), context.getDir("outdex", Context.MODE_PRIVATE).getAbsolutePath(), null, context.getClassLoader());
其中jarredDex
是一个jar文件与classes.dex
。罐子可以通过运行dx --dex --output=filename.jar your/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);
}
为什么你需要在运行时加载一个文件DEX? 5.0本机支持多个dex文件。 – ianhanniballake 2014-12-07 23:55:48
DEX文件包含敏感信息,并且在资产目录中进行了加密。当我需要使用它时,它会被解密,然后在运行时加载。 – garibay 2014-12-08 15:24:49
@garibay你能解决这个问题吗?我遇到同样的问题,这只适用于Dalvik。 – cdroid 2015-06-07 15:34:17