Integrate native library to Android gradle project — Sample project

Sarath DR
Technology and Digital Media
2 min readJun 11, 2015

--

Recently I have tried to integrate native libraries with some project. I could not find any good example or a better blog which explains it properly, especially when you integrate NDK with Gradle, the configuration is always a nightmare.

You can follow the below steps to add an native libraries to your android projects. Before you start make sure that you have downloaded android native development kit(NDK). Please find more details from the below link.

Step 1: Create a project with Android studio and add below line to local.properties file to include the NDK build system.

ndk.dir=/usr/local/android-ndk

Step 2: Create a new JNI folder in the main and then create Android.mk file as specified below.

# You can find more detail about this make file from the below link
# http://www.kandroid.org/ndk/docs/ANDROID-MK.html
# It basically describes the shared libraries to the NDK build system
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
# Specify the module name
LOCAL_MODULE := MyJni
LOCAL_SRC_FILES := my-jni.c

Step 3: Create my-jni.c inside your JNI folder with a method that returns a static string.

#include 
#include
jstring
Java_com_sarathdr_tech_nativeandroidapptest_MainActivity_stringFromJNI(JNIEnv* env, jobject callingObject)
{
return (*env)->NewStringUTF(env, "Fine! JNI is working ");
}

Step 4: Add the local module in build.gradle

defaultConfig {
applicationId "com.sarathdr.tech.nativeandroidapptest"
minSdkVersion 21
targetSdkVersion 22
versionCode 1
versionName "1.0"
ndk {
moduleName "MyJni"
}
}

Step 5: For testing, load the static module in main activity

public class MainActivity extends Activity {// Load native module here
static {
System.loadLibrary("MyJni");
}
// Add interface to the native method
public native String stringFromJNI();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String testString = stringFromJNI();TextView mainText = (TextView) findViewById(R.id.main_text);
mainText.setText(testString);
}
}

Finally: To import native shared libraries, follow below format. The below line imports OpenSL , android, log libraries to your project.

defaultConfig {
applicationId "com.example.nativeaudio"
minSdkVersion 14
targetSdkVersion 14
ndk {
moduleName "MyJni"
ldLibs "OpenSLES", "android", "log"
}
}

Add below line in the make file to load the shared libraries

include $(BUILD_SHARED_LIBRARY)

I have shared the sample project in GitHub, download it for more details. Google I/O 2015 announces that Android Studio 1.3 provides support for Native codes. So this will be much easier ;)

Git Project Link Download

--

--