2

I want to add .jar dynamically. So I make a demo. But I don't know how to new the DexClassLoader. I don't know how to add the first params.

final File optimizedDexOutputPath = new File("" + File.pathSeparator + "test.jar");
//PackageManager pm = getPackageManager();
String dexOutputDir = getApplicationInfo().dataDir;

DexClassLoader dexClassLoader = new DexClassLoader("",  dexOutputDir, null, getClassLoader());

I have made the dynamical .jar as test.jar(become dex) as well as a new folder 'text' in projects and put the text.jar in it.

Can you help me see what I have done wrong?

MikeMB
  • 20,029
  • 9
  • 57
  • 102
CoolEgos
  • 47
  • 1
  • 10

2 Answers2

0

The code to dynamically load a jar should look something like this:

//get the path to your .jar as a String
String jarPath = this.getApplicationContext().getFilesDir().getAbsolutePath();
jarPath += File.pathSeparator + "test" + File.pathSeparator + "test.jar";

//get a path to the directory you want to store odexs in as a String
String optimizedDir = this.getApplicationContext().getDir("odex", MODE_PRIVATE).getAbsolutePath();

//finally, call DexClassLoader
DexClassLoader dcl = new DexClassLoader( jarPath, optimizedDir, null, getClassLoader() );

The above assumes you've created a directory named "test" within your app's private files area and placed test.jar within that directory. You could create this directory and possibly copy test.jar from your app's assets area into this directory when your app first starts up.

Jared Rummler
  • 37,824
  • 19
  • 133
  • 148
awm129
  • 305
  • 2
  • 11
  • The second "File.PathSeparator" is ? @awm129 – CoolEgos Apr 16 '15 at 15:50
  • `optimizedDir = this.getApplicationContext().getDir("odex", MODE_PRIVATE).getAbsolutePath();` gets things like '/data/data/com.egos.example/app_odex' it can't work .and i can't create 'test' – CoolEgos Apr 16 '15 at 15:57
  • As I mentioned, you'll need to create that "test" directory and copy your .jar into it earlier in the code. You could use the same `Context.getDir()` method to create the "test" dir that I used here to create the odex directory. – awm129 Apr 16 '15 at 16:50
  • Yep. The jar needs to be on the phone. You may be able to put it in your assets area when you build the apk and then copy it to your new directory when your app is first run. – awm129 Apr 18 '15 at 03:05
0

Try this code:

// dexPath is the absolute path of your **DEX** file
ClassLoader loader = context.getClassLoader();      
dexLoader = new dalvik.system.DexClassLoader(**dexPath**, dexOutputDir, null, loader);
Verdigrass
  • 1,203
  • 12
  • 14