资讯专栏INFORMATION COLUMN

动态加载DEX

zhangke3016 / 3300人阅读

摘要:一什么是动态加载为什么要动态加载动态加载就是用到的时候再去加载,也叫懒加载,也就意味着用不到的时候是不会去加载的。

一.什么是动态加载?为什么要动态加载?

动态加载就是用到的时候再去加载,也叫懒加载,也就意味着用不到的时候是不会去加载的。

二.编写Demo 1.利用jar,dx 创建dex 1)创建DynamicDex.java,生成DynamicDex.class

2)生成dex




jar是JDK提供的,dx是Android SDK提供,只要配置好环境变量,可在任意位置执行
我是在debug中执行,方便使用
jar -cvf cn 生成jar包
dx --dex --output=target.jar source.jar 生成包含dex的jar包
注意:把dex放入assets后,把DynamicDex.java删掉或改名,否则加载的是它,而不是dex中的类

2.加载Dex

</>复制代码

  1. public class DexUtil {
  2. public static void loadDexClass(final Context context, final String dexName, final Handler handler) {
  3. new AsyncTask() {
  4. @Override
  5. protected String doInBackground(Void... params) {
  6. File cacheFile = getCacheDir(context.getApplicationContext());
  7. String internalPath = cacheFile.getAbsolutePath() + File.separator + dexName;
  8. Log.v("DexUtil", "internalPath = " + internalPath);
  9. File desFile = new File(internalPath);
  10. if (!desFile.exists()) {
  11. try {
  12. if (!desFile.exists()) {
  13. desFile.createNewFile();
  14. copyFiles(context, dexName, desFile);
  15. }
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. return internalPath;
  21. }
  22. @Override
  23. protected void onPostExecute(String internalPath) {
  24. super.onPostExecute(internalPath);
  25. File dexOutputDir = context.getDir("dex", 0);
  26. File soOutputDir = context.getDir("lib", 0);
  27. String librarySerachPath = soOutputDir.getAbsolutePath().replace("app_lib", "lib");
  28. Log.v("DexUtil", "librarySerachPath = " + librarySerachPath);
  29. DexClassLoader dexClassLoader = new DexClassLoader(internalPath, dexOutputDir.getAbsolutePath(),
  30. librarySerachPath, context.getClassLoader());//ClassLoader.getSystemClassLoader().getParent());
  31. Message msg = new Message();
  32. msg.obj = dexClassLoader;
  33. handler.sendMessage(msg);
  34. }
  35. }.execute();
  36. }
  37. public static void copyFiles(Context context, String fileName, File desFile) {
  38. InputStream in = null;
  39. OutputStream out = null;
  40. try {
  41. in = context.getApplicationContext().getAssets().open(fileName);
  42. out = new FileOutputStream(desFile.getAbsolutePath());
  43. byte[] bytes = new byte[1024];
  44. int i;
  45. while ((i = in.read(bytes)) != -1) {
  46. out.write(bytes, 0, i);
  47. }
  48. } catch (IOException e) {
  49. e.printStackTrace();
  50. } finally {
  51. try {
  52. if (in != null) {
  53. in.close();
  54. }
  55. if (out != null) {
  56. out.close();
  57. }
  58. } catch (IOException e) {
  59. e.printStackTrace();
  60. }
  61. }
  62. }
  63. public static boolean hasExternalStorage() {
  64. return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
  65. }
  66. /**
  67. * 获取缓存路径
  68. *
  69. * @param context
  70. * @return 返回缓存文件路径
  71. */
  72. public static File getCacheDir(Context context) {
  73. File cache;
  74. if (hasExternalStorage()) {
  75. cache = context.getExternalCacheDir();
  76. } else {
  77. cache = context.getCacheDir();
  78. }
  79. if (!cache.exists())
  80. cache.mkdirs();
  81. return cache;
  82. }
  83. }

Dex加载步骤:
1)把assets中的dex的jar拷贝到met目录下
文件拷贝需要添加权限

</>复制代码

2)利用DexClassLoader加载Dex,把dex放入到相关目录上


注意:文件的拷贝需要放在子线程中运行
3.利用反射加载

</>复制代码

  1. public class MainActivity extends AppCompatActivity {
  2. public static DexClassLoader mapLoader;
  3. TextView tv_hello;
  4. @Override
  5. protected void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.activity_main);
  8. tv_hello = (TextView) this.findViewById(R.id.tv_hello);
  9. DexUtil.loadDexClass(this, "dex_dynamic.jar", dexHandler);
  10. }
  11. private Handler dexHandler = new Handler() {
  12. @Override
  13. public void handleMessage(Message msg) {
  14. super.handleMessage(msg);
  15. mapLoader = (DexClassLoader) msg.obj;
  16. try {
  17. Class DynamicDex_Class = mapLoader.loadClass("cn.liufei.dynamicdex.DynamicDex");
  18. Constructor DynamicDex_Cons = DynamicDex_Class.getConstructor(null);
  19. Object DynamicDex_Obj = DynamicDex_Cons.newInstance();
  20. Method test_meth = DynamicDex_Class.getMethod("test", null);
  21. String result = (String) test_meth.invoke(DynamicDex_Obj, null);
  22. tv_hello.setText(result);
  23. } catch (ClassNotFoundException e) {
  24. e.printStackTrace();
  25. } catch (NoSuchMethodException e) {
  26. e.printStackTrace();
  27. } catch (IllegalAccessException e) {
  28. e.printStackTrace();
  29. } catch (InstantiationException e) {
  30. e.printStackTrace();
  31. } catch (InvocationTargetException e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. };
  36. }

Demo地址:链接: https://pan.baidu.com/s/1kVMQ6jX 密码: i4vp

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/70905.html

相关文章

发表评论

0条评论

zhangke3016

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<