- 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 <a href=’http://www.cygwin.com/’>Cygwin</a>.
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.