Using the Android NDK

    1. Create a regular Android project
    2. Add a new folder to your project – <project>/JNI
    3. 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");
      }
    4. 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)
    5. 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 <a href=’http://www.cygwin.com/’>Cygwin</a>.
The result is that a library file (.so file) will be created under < project>/lib.

  1. 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");
    }
  2. Use the native function in your java code. Example:
    TextView  tv = new TextView(context);
    tv.setText( getNativeString() );
  3. Compile and build the project.