DexClassLoader的构造函数:
- dexPath:dex文件路径
- optimizedDirectory:dex文件解压路径(一般是app的data目录)
- libraryPath:加载dex文件时需要用到的库的路径
- parent:父类加载
1、创建Itest接口以及testSDK类用于测试
public interface ITest {
void show(Context context,String message);
void hide(Context context,String message);
}
public class TestSDK implements ITest{
@Override
public void show(Context context, String message) {
Toast.makeText(context, message,Toast.LENGTH_LONG).show();
}
@Override
public void hide(Context context, String message) {
Toast.makeText(context, message,Toast.LENGTH_LONG).show();
}
}
2、把这两个类导出一个jar包(Eclipse或as工具)3、把导出的jar包生成dex文件,生成的test_dex.jar(用JD-gui查看,里面包含dex文件)放在assets文件夹下
dx --dex --output=test_dex.jar dynamic.jar
4、读取jar文件,并复制在缓存文件夹
public void copyFiles(Context context, String fileName, File desFile) { InputStream in = null; OutputStream out = null; try { in = context.getApplicationContext().getAssets().open(fileName); out = new FileOutputStream(desFile.getAbsolutePath()); byte[] bytes = new byte[1024]; int i; while ((i = in.read(bytes)) != -1) out.write(bytes, 0, i); } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); } } }
5、获取缓存文件
public boolean hasExternalStorage() { return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); } /** * 获取缓存路径 * * @param context * @return 返回缓存文件路径 */ public File getCacheDir(Context context) { File cache; if (hasExternalStorage()) { cache = context.getExternalCacheDir(); } else { cache = context.getCacheDir(); } if (!cache.exists()) cache.mkdirs(); return cache; }
6、DexClassLoader加载assets文件下的jar中的类
File cacheFile = getCacheDir(getApplicationContext()); String internalPath = cacheFile.getAbsolutePath() + File.separator + "test_dex.jar"; Log.e("tag","路径:"+internalPath+","+File.separator); File desFile = new File(internalPath); try { if (!desFile.exists()) { desFile.createNewFile(); copyFiles(VideoActivity.this,"test_dex.jar", desFile); } } catch (IOException e) { e.printStackTrace(); } String str=cacheFile.getAbsolutePath(); DexClassLoader dexClassLoader = new DexClassLoader(internalPath,cacheFile.getAbsolutePath(), null, this.getClass().getClassLoader()); try { Class clazz = dexClassLoader.loadClass("com.example.demo.TestSDK"); Method method = clazz.getMethod("show", Context.class, String.class); method.invoke(clazz.newInstance(), VideoActivity.this, "显示"); } catch (Exception e) { e.printStackTrace(); }
本文介绍如何使用DexClassLoader从Android应用的assets文件夹中加载自定义的.jar文件,并将其转换为.dex文件进行动态加载。包括创建接口及实现类、打包成jar、生成dex文件、读取并复制文件到缓存目录、使用DexClassLoader加载类的过程。

2227

被折叠的 条评论
为什么被折叠?



