动态versioncode_Android动态加载代码技术

48304ba5e6f9fe08f3fa1abda7d326ab.png

Class> cls = null;

try {

// 尝试第一种方法

cls = loadClass1(mainContext, pkg, entryCls);

} catch (Exception e) {

// 尝试第二种方法

cls = loadClass2(mainContext, pkg, entryCls);

}

// 示例代码

Object obj = cls.newInstance();

Method method = cls.getDeclaredMethod("someMethod");

method.invoke(obj);

// 第一种加载方法

private Class> loadClass1(Context mainContext, String pkg, String entryCls) throws Exception {

Context pluginContext = mainContext.createPackageContext(pkg, Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);

ClassLoader loader = pluginContext.getClassLoader();

return loader.loadClass(entryCls);

}

// 第二种加载方法

private Class> loadClass2(Context mainContext, String pkg, String entryCls) throws Exception {

Context pluginContext = mainContext.createPackageContext(pkg, Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);

String path = generatePluginDexPath(mainContext, pkg);

ensureFileExist(pluginContext, pkg, path);

// cacheDir必须是主程序的私有目录,否则DexClassLoader可能会拒绝加载

String cacheDir = mainContext.getApplicationInfo().dataDir;

ClassLoader parentLoader = pluginContext.getClassLoader();

DexClassLoader loader = new DexClassLoader(path, cacheDir, null, parentLoader);

return loader.loadClass(entryCls);

}

// 获取程序版本号

private int getVersionCode(Context context, String pkg) {

PackageInfo info = null;

int versionCode = 0;

try {

info = context.getPackageManager().getPackageInfo(pkg, PackageManager.GET_ACTIVITIES);

versionCode = info.versionCode;

} catch (Exception e) {}

return versionCode;

}

// 获取插件二进制代码的存储位置,注意做好版本控制;路径必须是以.dex结束,否则加载会出问题

private String generatePluginDexPath(Context context, String pkg) {

int version = getVersionCode(context, pkg);

String path = getMyAppPath() + ".classes/" + pkg + version + ".dex";

return path;

}

// 主程序在SD卡上的数据目录

private String getMyAppPath() {

return Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/";

}

// 拷贝插件的二进制代码到SD卡

private void ensureFileExist(Context pluginContext, String pkg, String path) throws Exception {

File file = new File(path);

if(file.exists()) return;

file.getParentFile().mkdirs();

Resources res = pluginContext.getResources();

int id = res.getIdentifier("classes", "raw", pkg);

InputStream in = res.openRawResource(id);

FileOutputStream out = new FileOutputStream(file);

try {

byte[] buffer = new byte[1024 * 1024];

int n = 0;

while((n = in.read(buffer)) > 0) {

out.write(buffer, 0, n);

} out.flush();

} catch (IOException e) {

in.close();

out.close();

}

}

48304ba5e6f9fe08f3fa1abda7d326ab.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值