Friday, September 19, 2014

Android - Load libraries at runtime

The Android compiler has a limitation of 65536 methods per .dex file. You can find a solution here, which tends to build your application to multiple dex files. However, if you need to add external libaries that make your application exceeds the limitation, we can come to another solution: copy the libraries somewhere except libs folder (assets folder, or sdcard), and load them at runtime. It seems easy, but we need to do some required steps to make it work.

1. Add dex file to libary jar file

We use dx command to create a dex file for the library:

dx --dex --output=classes.dex library.jar

Then, append it to the ordiginal library jar file with aapt command:

aapt add library.jar classes.dex

Notice that dx and aapt command are built tools of Android sdk, so they must in the classpath.

2. Load library file at runtime

Thanks to Nick Caballero for a nice solution to load a libary at runtime. You can go here to get Dexter class, which can be used as follow:

public class MainActivity extends Activity {
    private static String library = "library.jar";
    protected void onCreate(Bundle savedInstanceState) {
         try {
             Dexter.loadFromAssets(this, library);
         } catch (Exception e) {
             throw new RuntimeException("Unable to load DEX files", e);

         try {
              startActivity(new Intent(MainActivity.this,                                getClassLoader().loadClass("the real activity")));
         } catch (ClassNotFoundException e) {
              throw new RuntimeException("Unable to start", e);


Hope this helps!

No comments:

Post a Comment