DexClassLoader

DexClassLoader加载自己写的第三方jar包,例如金山毒霸需要加载ksremote.jar。

现在将DexClassLoader加载jar包成果分享一下。
   1.新建Android工程,封装功能java类。
   2.选中需要导出的文件夹,右键选中“Export”->"Java(Jar file)"导出jar文件。
   3.使用dx工具将jar包转换为android 字节码。
      命令:dx  --dex --Output=xx.jar    hello.jar
   4.将dx工具处理的xx.jar拷贝到工程raw目录下。
   5.在工程主Activity的onCreate函数中读取raw下的文件,并存储在当前应用目录。
      我的例子代码:
       InputStream inputStream = getResources().openRawResource(
        R.raw.mtnbinder);
    dexInternalStoragePath = new File(
        getDir(APP_JAR, Context.MODE_PRIVATE), DEX_NAME);
    if (!dexInternalStoragePath.exists()) {
      try {
        dexInternalStoragePath.createNewFile();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    
      FileOutputStream fileOutputStream = new FileOutputStream(
          dexInternalStoragePath);
      CopyFile.copyFile(inputStream, fileOutputStream);
        6.使用DexClassLoader调用jar包。
          我的例子代码:
           final File optimizedDexOutputPath = getDir(APP_JAR,
            Context.MODE_PRIVATE);
        try {
          DexClassLoader classLoader = new DexClassLoader(
              dexInternalStoragePath.getAbsolutePath(),
              optimizedDexOutputPath.getAbsolutePath(), null,
              getClassLoader());
          // com.mtn.binder.HookIPhoneSubInfo
          Class class1 = classLoader
              .loadClass("com.mtn.binder.HookIPhoneSubInfo");
          Method method = class1.getMethod("hook", new Class[] {});
          method.invoke(class1, new Object[] {});

             运行之后,就可以看到调用jar包成功。 

原文地址:https://www.cnblogs.com/kobe8/p/3822622.html