http://www.oschina.net/code/snippet_4873_3279#4874
代码片段(7)[全屏查看所有代码]
1. [代码]步骤 #1:使用ANT编译项目 NativeAdd.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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);
}
|
2. [代码]下面片断给出主activity中如何调用这个类/方法
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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()));
}
|
3. [代码]步骤#2:运行下面的命令产生头文件
1
|
javah -classpath ../../Android.jar;../bin/classes; org.apache.NativeAdd
|
4. [代码]新产生的头文件“(org_apache_CallNative.h”内容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
/* 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
|
5. [代码]步骤#3: 编写C文件如下“org_apache_NativeAdd.c”
1
2
3
4
5
6
7
|
#include "org_apache_NativeAdd.h"
JNIEXPORT jlong JNICALL Java_org_apache_NativeAdd_add
(JNIEnv *env, jclass c, jlong a, jlong b)
{
return
a + b;
}
|
6. [代码]步骤#5: 编译和连接 org_apache_NativeAdd.c/org_apache_NativeAdd.h为一个共享库.
1
2
|
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
|
7. [代码]步骤 #6: 复制编译文件到模拟器中. 同时安装APK程序.
1
2
|
adb push native
/libNativeAdd
.so
/system/lib
adb
install
bin
/CallNative
.apk
|