Rahul's Tech Blog

Growth Hacking, Just Hacking or No hacking !!!

Hello World JNI program in NDK using

 

Create new android application

Create a new native method

public native String nativeFunction();

Then run this command from inside /app/src/main

javah -d jni -classpath /Applications/adt-20140624/sdk/platforms/android-19/android.jar:../../build/intermediates/classes/debug:/Applications/adt-20140624/sdk/extras/android/support/v7/appcompat/libs/android-support-v4.jar:/Applications/adt-20140624/sdk/extras/android/support/v7/appcompat/libs/android-support-v7-appcompat.jar com.rahulprasad.www.ndksample.MainActivity

This will create jni folder inside src
This will also create a header file called com_rahulprasad_www_ndksample_MainActivity.h

Duplicate the header file as main.c
and remove everything except function initialization. Include header in main.c It should look like this

#include "com_rahulprasad_www_ndksample_MainActivity.h"
JNIEXPORT jstring JNICALL Java_com_rahulprasad_www_ndksample_MainActivity_nativeFunction
   (JNIEnv *, jobject);

Now complete the function

JNIEXPORT jstring JNICALL Java_com_rahulprasad_www_ndksample_MainActivity_nativeFunction
   (JNIEnv *env, jobject obj) {
     return (*env)->NewStringUTF(env, "Hello from JNI");
   }

Now to build the project android studio must know the location of NDK. Download NDK if you don’t have it and it to local.properties

ndk.dir=/Users/rahulprasad/Development/Android/android-ndk-r10e

Now Build > Make Project
It should generate .so files under app/intermediates/ndk/debug/lib/*/libapp.so

You can change the name of .so files from build.gradle, Just add it inside defaultConfig

ndk {
    moduleName "MyLib"
}

To use native function, Library must be loaded. You can do that by adding this to class

static {
    System.loadLibrary("MyLib");
}

Then you can use the native function directly. For example:

TextView tv = (TextView)findViewById(R.id.my_textview);
tv.setText(nativeFunction());