Wednesday 12 March 2014

Learn The NDK,Compile JNI (Java Native Interface) using android NDK (Native Development kit)

It is boring to know things without visualization as we think, pictures comes in our mind so let’s experience it with an example and create an image in your mind. Before we go I assume you have done all setup for Android and have knowledge of Android SDK.

Step 1: First create a project then create a folder named jni in your project directory.
Figure: 1

Step 2: Create addition.c file in jni folder and add the below lines.
#include "com_ndkadd_Addition_Addition.h"
#include <jni.h>
jint Java_com_ndkadd_Addition_Addition_mAdd(JNIEnv * env, jobject jObj, jint value1, jint value2) { return (value1 + value2);}

Step 3: Create Android.mk file in jni folder and add the below code
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := Addition
LOCAL_SRC_FILES := addition.c
include $(BUILD_SHARED_LIBRARY)


Step 4: Below the code for your activity and usage of created .so file in your libs folder.
public class Addition extends Activity {
static
{
System.loadLibrary("Addition");
}
public native int mAdd(int v1,int v2);
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tAdd= new TextView(this);
tAdd.setText(""+mAdd(5,5));
setContentView(tAdd);
}
}


Step 5: Now we need to generate header files so make sure you have java installed and all environment variables set. Navigate to classes folder under bin folder of your project directory (in my case it’s “D:\WorkSpace\Addition\bin\classes”) from command prompt and execute the following command.
javah -jni com.ndkadd.Addition.Addition
(*”com.ndkadd.Addition” is my package name so replace it with your’s and “Addition” is my class name)

Step 6: Above command results in a com_ndkadd_Addition_Addition.h file under classes folder of your project directory so copy the created com_ndkadd_Addition_Addition.h file to jni folder of your project in eclipse.

Step 7: Now set environment variable for NDK as shown in figure below:-

No comments:

Post a Comment