How can I add a static library to Android NDK using the build.gradle file?

3.7k views Asked by At

I'm trying to learn to use the NDK in AndroidStudio, and I'd like to import the "android_native_app_glue" file used in the "native-activity" sample, so that I have a framework for basic functions like the display, touch, etc. In the sample, it loads the library with this line in the android.mk file:

LOCAL_STATIC_LIBRARIES := android_native_app_glue

and then imports it in "main.c" simply with:

#include <android_native_app_glue.h>

But in AndroidStudio, as far as I can tell from experimenting with it, it doesn't use the android.mk file at all and instead uses the build.gradle file to do all the same functions instead. So, for example, to replace LOCAL_LDLIBS := ... in the android.mk, I used ldLibs = ... in the build.gradle. What gradle code replaces LOCAL_STATIC_LIBRARIES?

Is there also a resource somewhere that explains, in general, how to translate from android.mk to build.gradle?

1

There are 1 answers

3
ph0b On

if you really want to make it work without Makefiles, you can copy and paste ndk\sources\android\native_app_glue\android_native_app_glue.(c|h) into your jni folder and add android to your ldLibs.

Else, you can still rely on classic Makefiles, by deactivating the default call to ndk-build, and making gradle use your libs from the libs directory:

sourceSets.main {
    jniLibs.srcDir 'src/main/libs'
    jni.srcDirs = [] //disable automatic ndk-build call
}

In that case you'll have to call ndk-build yourself, but you can also make gradle call it for you:

// call regular ndk-build(.cmd) script from app directory
task ndkBuild(type: Exec) {
    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
        commandLine 'ndk-build.cmd', '-C', file('src/main').absolutePath
    } else {
        commandLine 'ndk-build', '-C', file('src/main').absolutePath
    }
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn ndkBuild
}