2. 编写HelloJni工程,在主Activity(本例:HelloJni.java)里声明native函数:
如下:
public native String stringFromJNI();
public native double add(double a, double b);
public native double sub(double a, double b);
public native double multi(double a, double b);
public native double div(double a, double b);
static {
System.loadLibrary("hello-jni");
}
3. 在根目录下创建 jni 目录(mkdir jni).
4. 利用命令生成相应的头文件,在根目录下执行:javah -classpath bin/classes -d jni com.xxx.hello.HelloJni
————————————— ———————
^ ^
包名 类名
5. 编写相应的.c文件(hello-jni.c)
#include<string.h>
#include<jni.h>
JNIEXPORT jstring JNICALL Java_com_xxx_hello_HelloJni_stringFromJNI(JNIEnv *env, jobject obj)
{
return(*env)->NewStringUTF(env, "Hello World from JNI !");
}
JNIEXPORT jdouble JNICALL Java_com_xxx_hello_HelloJni_add(JNIEnv *env, jobject obj, jdouble a, jdouble b)
{
return a + b;
}
JNIEXPORT jdouble JNICALL Java_com_xxx_hello_HelloJni_sub(JNIEnv *env, jobject obj, jdouble a, jdouble b)
{
return a - b;
}
JNIEXPORT jdouble JNICALL Java_com_xxx_hello_HelloJni_multi(JNIEnv *env, jobject obj, jdouble a, jdouble b)
{
return a * b;
}
JNIEXPORT jdouble JNICALL Java_com_xxx_hello_HelloJni_div(JNIEnv *env, jobject obj, jdouble a, jdouble b)
{
return a / b;
}
6. jni目录下编写Android.mk文件
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := hello-jni
LOCAL_SRC_FILES := hello-jni.c
include $(BUILD_SHARED_LIBRARY)
在根目录下运行:ndk-build
xxx@xion-driver:~/android_env/eclipse/Workspace/HelloJni$ndk-build
Install : libhello-jni.so => libs/armeabi/libhello-jni.so
可以看到已经正确的生成了libhello-jni.so共享库了。
7. Eclipse运行该工程即可。
~~完~~