How to use Native Development Kit (NDK) in Android

NDK (Native Development Kit) is a set of tools that enables you to easily include native code written in C or C++ in your Android applications. The NDK uses the JNI mechanism to call functions from Java to C and C++. The NDK was introduced with Android version 1.5. In version 2.3 some major improvements were added like lifecycle events callbacks.

In many cases using a native code can reproduce better performance. You may want to use existing C or C++ libraries in your application.

Download NDK from: http://developer.android.com/sdk/ndk/index.html according to your development OS.

Using the NDK

Here’s how to use the NDK.

Create a regular Android project. Add a new folder to your project – <project>/JNI. Write a native (C/C++) code and place the files under <project>/JNI. You should follow the JNI rules when writing your native code. Example:

#include <string.h>
#include <jni.h>

jstring
Java_com_mypackage_helloworld_HelloWorld_getNativeString( JNIEnv* env, jobject obj )
{
    return (*env)->NewStringUTF(env, "Hello World");
}

Create a Android.mk file and also put it under <project>/JNI. Android.mk describes how to build the native libraries. Example:

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE    := hello
LOCAL_SRC_FILES := hello.c
include $(BUILD_SHARED_LIBRARY)

Compile and build the native code using the ‘ndk-build’ script. Go to your android project and run the command:

<path to NDK home>/ndk-build

This is a Unix command so if you are developing on windows you will need to use a tool called Cygwin.
The result is that a library file (.so file) will be created under <project>/lib.
Add the native java code – add a code that loads the native code and also the native API. The simplest way is to add those to your activity class. Example:

public native String  getNativeString();

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

Use the native function in your java code. Example:

TextView  tv = new TextView(context);
tv.setText( getNativeString());

Compile and build the project.

For more android tutorials check out Tutorial for Android developer app.

Tutorial for Android developer app

Software Engineer(Android) at Bennett Coleman and Co. Ltd. (Times Group)

This content has been helpful to you?

Thanks for contributing!

Yes No