Android 开发中 JAVA 调用 C++

[代码] 步骤 #1:使用ANT编译项目 NativeAdd.java
view sourceprint?01 package org.apache; 

02   

03 import Android.util.Log; 

04   

05 public class NativeAdd { 

06     static { 

07         try { 

08             Log.i("JNI", "Trying to load libNativeAdd.so"); 

09             System.loadLibrary("NativeAdd"); 

10         } 

11         catch (UnsatisfiedLinkError ule) { 

12             Log.e("JNI", "WARNING: Could not load libNativeAdd.so"); 

13         } 

14     } 

15   

16     public static native long add(long a, long b); 

17 }
[代码] 下面片断给出主activity中如何调用这个类/方法
view sourceprint?
01 public void onClick(View view) { 

02       Log.i(LOG_TAG, "onClick"); 

03  

04       EditText a = (EditText) findViewById(R.id.a); 

05       EditText b = (EditText) findViewById(R.id.b); 

06       EditText c = (EditText) findViewById(R.id.c); 

07       Log.i(LOG_TAG, "calling native method"); 

08       long sum = NativeAdd.add( Long.parseLong(a.getText().toString()), 

09               Long.parseLong(b.getText().toString())); 

10       Log.i(LOG_TAG, "back from native method"); 

11       String text = Long.toString(sum); 

12       c.setText("Native add returns = " + text.subSequence(0, text.length())); 

13   }
[代码] 步骤#2:运行下面的命令产生头文件
view sourceprint?
1 javah -classpath ../../Android.jar;../bin/classes; org.apache.NativeAdd
[代码] 新产生的头文件“(org_apache_CallNative.h”内容如下
view sourceprint?
01 /* DO NOT EDIT THIS FILE - it is machine generated */

02 #include 

03 /* Header for class org_apache_NativeAdd */

04   

05 #ifndef _Included_org_apache_NativeAdd 

06 #define _Included_org_apache_NativeAdd 

07 #ifdef __cplusplus 

08 extern "C" { 

09 #endif 

10 /* 

11  * Class:     org_apache_NativeAdd 

12  * Method:    add 

13  * Signature: (JJ)J 

14  */

15 JNIEXPORT jlong JNICALL Java_org_apache_NativeAdd_add 

16   (JNIEnv *, jclass, jlong, jlong); 

17   

18 #ifdef __cplusplus 

19 } 

20 #endif 

21 #endif
[代码] 步骤#3: 编写C文件如下“org_apache_NativeAdd.c”
view sourceprint?
1 #include "org_apache_NativeAdd.h" 

2   

3 JNIEXPORT jlong JNICALL Java_org_apache_NativeAdd_add 

4   (JNIEnv *env, jclass c, jlong a, jlong b) 

5 { 

6     return a + b; 

7 }
[代码] 步骤#5: 编译和连接 org_apache_NativeAdd.c/org_apache_NativeAdd.h为一个共享库.
view sourceprint?
1 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 

2 arm-none-linux-gnueabi-ld -T armelf_linux_eabi.xsc -shared -o libNativeAdd.so org_apache_NativeAdd.o
[代码] 步骤 #6: 复制编译文件到模拟器中. 同时安装APK程序.
view sourceprint?
1 adb push native/libNativeAdd.so /system/lib 

2 adb install bin/CallNative.apk

你可能感兴趣的:(java,C++,c,android,C#)