android 动态 dex,在Android 5.0上动态加载DEX文件

Miha_x64..

6

更新

这适用于Dalvik和ART:new DexClassLoader(jarredDex.getAbsolutePath(), context.getDir("outdex", Context.MODE_PRIVATE).getAbsolutePath(), null, context.getClassLoader());哪里jarredDex是jar文件classes.dex.Jar可以通过运行获得dx --dex --output=filename.jar your/classes/dir.

原始答案

我从这篇文章中获取了一个代码示例.但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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值