这篇文章仅做个人学习记录和积累。如果新手入门,请看 http://www.cnblogs.com/hibraincol/archive/2011/05/30/2063847.html 个人觉得写的很完整和详细。

NDK 和 jni 的关系百度下遍地都是。我是用的开发环境是 ubuntu+eclipse+ndk 

1.创建应用,在activity中 声明本地方法 ,add() 就是我们需要使用c/c++去实现的方法。

 1 public class MainActivity extends Activity {
 2 
 3     TextView tv ;
 4     @Override
 5     protected void onCreate(Bundle savedInstanceState) {
 6         super.onCreate(savedInstanceState);
 7         setContentView(R.layout.activity_main);
 8         tv = (TextView)findViewById(R.id.tv);
 9         tv.setText("user dongtai zhuce : s"+add(10,30));
10     }
11     static
12     {
13         System.loadLibrary("main");
14     }
15 
16     
17     public static native int add(int x,int y);
18 }

2.我使用的动态注册.不需要生成头文件。代码如下:

 1 #include <jni.h>
 2 #include <string.h>
 3 //不管是动态注册还是静态注册我们的方法中都要有JNIEnv* 和 jobject两个对象
 4 int add(JNIEnv* env,jobject thiz,int x,int y)
 5 {
 6     return x+y;
 7 }
 8 
 9 /**
10 * 方法对应表
11 */
12 static JNINativeMethod gMethods[] = {
13     {"add", "(II)I", (void*)add},//绑定
14 };
15 
16 
17 /*
18 * 为某一个类注册本地方法
19 */
20 static int registerNativeMethods(JNIEnv* env
21         , const char* className
22         , JNINativeMethod* gMethods, int numMethods) {
23     jclass clazz;
24     clazz = (*env)->FindClass(env, className);
25     if (clazz == NULL) {
26         return JNI_FALSE;
27     }
28     if ((*env)->RegisterNatives(env, clazz, gMethods, numMethods) < 0) {
29         return JNI_FALSE;
30     }
31 
32     return JNI_TRUE;
33 }
34 
35 /*
36 * 为所有类注册本地方法
37 */
38 static int registerNatives(JNIEnv* env) {
39     const char* kClassName = "org/pqp/testnativejni/MainActivity";//指定要注册的类
40     return registerNativeMethods(env, kClassName, gMethods,
41             sizeof(gMethods) / sizeof(gMethods[0]));
42 }
43 
44 
45 /*
46 * System.loadLibrary("lib")时调用
47 * 如果成功返回JNI版本, 失败返回-1
48 */
49 jint JNI_OnLoad(JavaVM* vm, void* reserved) {
50     JNIEnv* env = NULL;
51     jint result = -1;
52 
53     if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_4) != JNI_OK) {
54         return -1;
55     }
56 
57     if (!registerNatives(env)) {//注册
58         return -1;
59     }
60     //成功
61     result = JNI_VERSION_1_4;
62 
63     return result;
64 }

以上是我使用c去实现的一个本地方法的实现。当然c++也可以实现。原理都是一样的。

3.编写mk文件,使用交叉编译环境生成我们需要的动态链接文件,在ubuntu上格式为so。

1 LOCAL_PATH := $(call my-dir)
2 include $(CLEAR_VARS)
3 LOCAL_MODULE    := main
4 LOCAL_SRC_FILES := Main.c
5 include $(BUILD_SHARED_LIBRARY)

注意mk文件的命令为 Android.mk.有关mk文件的详细用法可以自己百度下。

4.最后一步,这里成功不了,前面的努力都白费了。编译环境很重要,在window上编译有点麻烦。所以还是找台linux的机器。然后下个ndk就可以搞定了。如果有源码的编译环境那当然是最好不过了的哦。

进入项目所在的目录;在项目的根目录下:$NDK/ndk-build  有如下输出那么你就搞定了。

ok。关机休息。

 

 

 

posted on 2014-03-29 01:42  Royal.king  阅读(291)  评论(0)    收藏  举报