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().
To call the NDK function, we need to declare the function.
We can then call the NDK method.
With APKs from both projects installed on my phone, I got the following results.
Figure 2. Execution Results