How to Deploy Android NDK Library in Separate APK

There’re times developers want to deploy a NDK library in a separate APK. A typical use case is your library is big and it has different versions for different CPUs/phones. A naive strategy is to put all those libraries in a single huge apk and get lots of user complains. A better approach is to separate NDK library from the main application. This has been done by many video player apps.

Recently I also adopted this approach for my Video Converter Android app. This post gives a simple example of using separate APK for native library.

0. Create the NDK Library

The first step is to create the NDK library. We used the hello-jni code in the NDK sample. Note that when creating this project, uncheck the “Create Activity” box, since we’re going to create a apk contains NDK library only. This is shown in figure below,

Figure 1. Creating a Native Library

You can download the code at the end of this post.

Note that the package name for the library project is roman10.tutorial.nativelib. Once you export the apk and installed it on your device, the ndk library “libhello-jni.so” will be put at /data/data/roman10.tutorial.nativelib/lib/.

Note that the NDK library function’s signature needs to follow the JNI standard in order for the project code described below to call it.

1. Create a Project that Use the NDK Library

Now we create a project that uses the NDK library. To load the library, instead of loadLibrary function, we use load().

private static final String libPath = "/data/data/roman10.tutorial.nativelib/lib/libhello-jni.so";

System.load(libPath);

To call the NDK function, we need to declare the function.

public native String  stringFromJNI();

We can then call the NDK method.

displayText = (TextView) findViewById(R.id.display);        

displayText.setText( stringFromJNI() );

With APKs from both projects installed on my phone, I got the following results.

Figure 2. Execution Results

2. Downloads

You can download the code for the two projects here, from get them from my github here.

Leave a Reply

Your email address will not be published. Required fields are marked *