2010年10月17日 星期日

[Android] Write a JNI interface for your Android application

Write a JNI Interface for Android Application

Jing (mqJing@msn.com)


Download: hellojni.zip

Outline
Use Your Native Function
  • [Java] Write your java code -> apk

Create the Library
  • [C header] Generate the function prototype
  • [C] Implement the function
  • [Android] Write a make file
  • Put all files in to the “external” or “development” directory
  • [Make] goto the source root and make the module

Testing
  • Build & Burning the Image
  • adb install your_application.apk



Content
Step 1: [Java] Write your java code

package name: hellojni.hellojni

class name:hellojni.java

*



Create the Library
Step 2: [C header] Generate the function prototype

a. Build the code: hellojni

b. Make sure you path: at bin

a. Build the code to generate class file (You can use Eclipse to do this)
b. Make sure your path: bin
bin
| ---hellojni
| ---- hellojni
| ----- hellojni.class


c. Generate the header file
Command:
javah -jni .
ex:
bin\>javah hellojni.hellojni.hellojni

Result:



Step 3: [C] Implement the function

hellojni.c

#include

#define LOG_TAG "ABC_lib"
#undef LOG
#include

JNIEXPORT jint JNICALL Java_hellojni_hellojni_hellojni_addTest(JNIEnv *env, jclass cls, jint x, jint y){
// 你可以用 adb 連進 device, 用 logcat 看資料
LOGD("Java_hellojni_hellojni_hellojni_addTest");
return x+y;
}


Step 4: [Android] Write a make file

Android.mk

# 一開始要加這段
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)

# 指定要編譯的原始檔
LOCAL_SRC_FILES:= \
hellojni.c

# 設定 .h 檔搜尋目錄
LOCAL_C_INCLUDES := \
$(JNI_H_INCLUDE)

# 這個 .c 檔要使用 libutils library
LOCAL_SHARED_LIBRARIES := \
libutils

# 不使用 prelink
LOCAL_PRELINK_MODULE := false

# [輸出] 表明需要編成 share libaray
# 會產生 out/target/product/xxx/obj/lib/libhellojni.so
LOCAL_MODULE := libhellojni
include $(BUILD_SHARED_LIBRARY)


Step 5: Put all files in to the “external” or “development” directory


Step 6: [Make] goto the source root and make the module
Command:
$make <你定義的 LOCAL_MODULE name>
Ex:
$make libhellojni



Testing
Step 1: build image
Step 2: burn image
Step 3: adb install your_application.apk

Reference:
  1. http://www.top-e.org/jiaoshi/html/?168.html