Using Pre-built Shared Library In Android Studio
Solution 1:
I was able to make it work using Android.mk instead of cmake. I am posting configurations and contents of Android.mk and gradle build just in case any one needs it.
Create a folder "jni" under "app". Create another custom folder "yourlibs" and put all your pre-built libs inside this "yourlibs" folder in respective "TARGET_ARCH_ABI" folder. For Example, in my case:
- jni/yourlibs/armeabi/libdynamic.so
- jni/yourlibs/armeabi-v7a/libdynamic.so
- jni/yourlibs/x86/libdynamic.so
- jni/yourlibs/x86_64/libdynamic.so
Now follow these steps:
- Create a "C" file inside the "jni" folder from where you would call the function defined inside the "libdynamic.so". Add neccesary header files to your created "C" file. For me it is "uselib.c" and "header.h"
- Create a file named "Android.mk" inside the "jni" folder
Add following contents in Android.mk
LOCAL_PATH := $(call my-dir)include$(CLEAR_VARS)
LOCAL_SRC_FILES := yourlibs/$(TARGET_ARCH_ABI)/libdynamic.so
LOCAL_MODULE := add_prebuilt
include$(PREBUILT_SHARED_LIBRARY)include$(CLEAR_VARS)
LOCAL_SRC_FILES := uselib.c
LOCAL_MODULE := use-lib
LOCAL_SHARED_LIBRARIES := add_prebuilt
include$(BUILD_SHARED_LIBRARY)
Update gradle build (app) file to use "Android.mk" instead of cmake:
Inside "android => defaultConfig"
ndk{
abiFilters 'armeabi', 'armeabi-v7a', 'x86', 'x86_64'
}
Inside "android"
externalNativeBuild {
ndkBuild {
path"jni/Android.mk"
}
}
This will make a library called "use-lib" that uses "libdynamic.so" and it will pack both the libraries inside the lib folder of apk. You can check this using apk analyser (Android Studio => Build => Analyse Apk ...). To use "use-lib" use jni call, like:
static {
System.loadLibrary("use-lib");
}
public native String stringFromJNI();
Note: I removed extern "C" statement from the C code.
Solution 2:
In order to load your library with CMake in Android environment you will have to add the following code in native-lib CMakeLists.txt:
Set your libs path
set(LIBS_DIR ${CMAKE_SOURCE_DIR}/../jniLibs)
Add library to import
add_library(DYNAMIC_LIB SHARED IMPORTED)
Set library location for each ABI
set_target_properties(DYNAMIC_LIB PROPERTIES
IMPORTED_LOCATION ${LIBS_DIR}/${ANDROID_ABI}/lidynamic.so)
Link imported library to target
target_link_libraries(native-lib DYNAMIC_LIB)
and in the native-lib build.gradle:
defaultConfig{
...
externalNativeBuild{
// Specify the toolchain which was used to cross compile libdynamic.so because Android Studio assumes that you used clangarguments'-DANDROID_TOOLCHAIN=gcc'
}
}
Solution 3:
Add the sysroot lib dir to LDFLAGS using -L since if I recall correctly libdynamic also relies on libc, libdl, and should require libm at the very least.
The path should be:
$NDK/platforms/android-(platform-version)/arch-(architecture)/usr/lib
Post a Comment for "Using Pre-built Shared Library In Android Studio"