Android动态加载jar/dex遇到的问题
想法:实现与腾讯游戏大厅融合自身开发游戏的方式,安装了游戏大厅后对于腾讯自主研发的游戏比如:斗地主,用户无需安装就可以直接使用。
设计思路:把子apk放到assets目录中,在主程序中将此apk拷贝到SD卡中,用动态加载方式去调用。
实现:
public void loadAPK(Bundle paramBundle, String dexpath, String dexoutputpath) { ClassLoader localClassLoader = ClassLoader.getSystemClassLoader(); DexClassLoader localDexClassLoader = new DexClassLoader(dexpath, dexoutputpath, null, localClassLoader); try { PackageInfo plocalObject = getPackageManager().getPackageArchiveInfo(dexpath, 1); if ((plocalObject.activities != null)&& (plocalObject.activities.length > 0)) { String activityname = plocalObject.activities[0].name; Log.d(TAG, "activityname = " + activityname); Class localClass = localDexClassLoader.loadClass(activityname); Constructor localConstructor = localClass.getConstructor(new Class[] {}); Object instance = localConstructor.newInstance(new Object[] {}); Log.d(TAG, "instance = " + instance); Method localMethodSetActivity = localClass.getDeclaredMethod("setActivity", new Class[] { Activity.class }); localMethodSetActivity.setAccessible(true); localMethodSetActivity.invoke(instance, new Object[] { this }); Method methodonCreate = localClass.getDeclaredMethod("onCreate", new Class[] { Bundle.class }); // Method methodonCreate = localClass.getDeclaredMethod("init", new Class[]{String.class}); methodonCreate.setAccessible(true); methodonCreate.invoke(instance, paramBundle); } return; } catch (Exception ex) { ex.printStackTrace(); } }
采用以上方法在外置SD卡(/mnt/sdcard/)上可以启动子apk,但在内置SD卡(/storage/sdcard0)中无法启动,报错语句:
DexClassLoader localDexClassLoader = new DexClassLoader(dexpath, dexoutputpath, null, localClassLoader);
错误信息如下:
java.lang.IllegalArgumentException: Optimized data directory /storage/sdcard0 is not owned by the current user. Shared storage cannot protect your application from code injection attacks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
指定dexoutputpath为APP自己的缓存目录即可。
详见http://blog.csdn.net/yangjunjiezai/article/details/8668265
.dex文件在4.1之后是不能保存在sd卡下的