ubuntu jni NDK 开发简介

这篇文章仅作我的学习记录和积累。若是新手入门,请看 http://www.cnblogs.com/hibraincol/archive/2011/05/30/2063847.html 我的以为写的很完整和详细。html

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

1.建立应用,在activity中 声明本地方法 ,add() 就是咱们须要使用c/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.我使用的动态注册.不须要生成头文件。代码以下:ubuntu

 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++也能够实现。原理都是同样的。eclipse

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

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就能够搞定了。若是有源码的编译环境那固然是最好不过了的哦。ui

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

ok。关机休息。code

相关文章
相关标签/搜索