步骤 #1:使用ANT编译项目.
NativeAdd.java class
package org.apache;
import Android.util.Log;
public class NativeAdd {
static {
try {
Log.i("JNI", "Trying to load libNativeAdd.so");
System.loadLibrary("NativeAdd");
}
catch (UnsatisfiedLinkError ule) {
Log.e("JNI", "WARNING: Could not load libNativeAdd.so");
}
}
public static native long add(long a, long b);
}
下面片断给出主activity中如何调用这个类/方法
public void onClick(View view) {
Log.i(LOG_TAG, "onClick");
EditText a = (EditText) findViewById(R.id.a);
EditText b = (EditText) findViewById(R.id.b);
EditText c = (EditText) findViewById(R.id.c);
Log.i(LOG_TAG, "calling native method");
long sum = NativeAdd.add( Long.parseLong(a.getText().toString()),
Long.parseLong(b.getText().toString()));
Log.i(LOG_TAG, "back from native method");
String text = Long.toString(sum);
c.setText("Native add returns = " + text.subSequence(0, text.length()));
}
步骤#2:运行下面的命令产生头文件
javah -classpath ../../android.jar;../bin/classes; org.apache.NativeAdd
新产生的头文件“(org_apache_CallNative.h”内容如下
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class org_apache_NativeAdd */
#ifndef _Included_org_apache_NativeAdd
#define _Included_org_apache_NativeAdd
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: org_apache_NativeAdd
* Method: add
* Signature: (JJ)J
*/
JNIEXPORT jlong JNICALL Java_org_apache_NativeAdd_add
(JNIEnv *, jclass, jlong, jlong);
#ifdef __cplusplus
}
#endif
#endif步骤#3: 编写C文件如下“org_apache_NativeAdd.c”:#include "org_apache_NativeAdd.h"
JNIEXPORT jlong JNICALL Java_org_apache_NativeAdd_add
(JNIEnv *env, jclass c, jlong a, jlong b)
{
return a + b;
}步骤#4: Please read the following article before you try the next step. Shared library “Hello World!” for Android步骤#5: 编译和连接 org_apache_NativeAdd.c/org_apache_NativeAdd.h为一个共享库.
arm-none-linux-gnueabi-gcc -I/usr/lib/jvm/java-1.5.0-sun/include -I/usr/lib/jvm/java-1.5.0-sun/include/linux -fpic -c org_apache_NativeAdd.c
arm-none-linux-gnueabi-ld -T armelf_linux_eabi.xsc -shared -o libNativeAdd.so org_apache_NativeAdd.o
注意: armelf_linux_eabi.xsc的细节内容在步骤4中给出
步骤 #6: 复制编译文件到模拟器中. 同时安装APK程序.
adb push native/libNativeAdd.so /system/lib
adb install bin/CallNative.apk
步骤 #7:运行程序查看结果。