Search code examples
androidandroid-ndkandroid-gradle-pluginaarmaven-central

Android AAR package for native library


I'm looking for a way to package a native library into an AAR package, so it would be possible to use it via dependencies declaration in gradle script.

By native library I mean set of .cpp files or compiled static library and a set of header files. So, I mean that the app itself will call the library from native code, not from Java. In other words, the library needed to compile app's native code. So that it will be possible to easily manage dependencies of native code.

Is it even possible?

So far I could only find a lot of questions/examples of how to make an AAR of JNI native library with .so file and its Java interface, so the lib just a Java lib with native implementation, but this is not what I need.


Solution

  • Manually hacking the gradle scripts works, but is painful and error-prone.

    I've recently found a plugin that magically bundles the headers into the AAR files and extracts them and sets up the build scripts when adding the dependency: https://github.com/howardpang/androidNativeBundle

    On the reusable library:

    • Add the export plugin:

      apply plugin: 'com.ydq.android.gradle.native-aar.export'
      
    • Define where the header files are:

      nativeBundleExport {
          headerDir = "${project.projectDir}/src/main/jni/include"
      }
      

    On the module that uses it:

    • Add the import plugin:

      apply plugin: 'com.ydq.android.gradle.native-aar.import'
      
    • add include ${ANDROID_GRADLE_NATIVE_BUNDLE_PLUGIN_MK} to each module that depends on it in your Android.mk:

      include $(CLEAR_VARS)
      LOCAL_SRC_FILES := myapp.cpp \
      LOCAL_MODULE := myapp
      LOCAL_LDLIBS += -llog
      include ${ANDROID_GRADLE_NATIVE_BUNDLE_PLUGIN_MK}
      include $(BUILD_SHARED_LIBRARY)