Dynamic loading in Android.jar implementation steps

  • 2020-05-09 19:15:27
  • OfStack

First of all, the first one is the production of jar file. It is ok to package the.class file into the.jar file in Java. However, Dalvik VM of Android does not recognize byte code of Java. Of course, once the dx tool is switched, the jar package is no longer a.class file, but a.dex file.

The second is that Android also provides an implementation of URLClassLoader, but it doesn't work. To dynamically load other classes, Class Loader can be used:
DexClassLoader, PathClassLoader, where DexClassLoader can load apk, jar or dex files, for example:
 
File jarFile = new File("/sdcard/test.dex"); 
# if ( jarFile.exists() ) { 
DexClassLoader cl = new DexClassLoader(jarFile.toString(), "/sdcard/test", null, ClassLoader.getSystemClassLoader()); 
Class<?> c = cl.loadClass("xiaogang.test.Test"); 

However, DexClassLoader requires that you specify a writable directory, the second parameter of the DexClassLoader constructor, which in the above example is /sdcard/test
This parameter means: directory where optimized DEX files should be written
Because Dalvik is dynamically optimized when loading dex files, DexClassLoader requires that the location of dex files after optimization be specified.

PathClassLoader is even more limited in that it can only load apk files already installed on the Android system, which is apk files in the /data/app directory. ClassNotFoundException will appear when files from other locations are loaded. For example:

PathClassLoader cl = new PathClassLoader(jarFile.toString(), "/data/app/" , ClassLoader.getSystemClassLoader()); 

Since PathClassLoader will read the dex files optimized by Dalvik in the directory /data/ dalvik-cache, the dex files of this directory were generated by Dalvik when the apk package was installed. . For example, if the package name is xiaogang test, Android application after installation is stored in the/data/app recorded, namely/data app/xiaogang test - 1. apk, so/data/dalvik - cache directory will generate data @ app@xiaogang.test-1.apk. @ classes dex file. When calling PathClassLoader, it will find the dex file according to this rule. If the apk file you specified is /sdcard/ test.apk, it will read /data/dalvik-cache/sdcard@test.apk@classes.dex file according to this rule. Obviously, this file will not exist, so PathClassLoader will report an error.

Until Google fixes this issue, we'll either have to use DexClassLoader or PathClassLoader to load the installed apk.

Related articles: