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

相關文章
相關標籤/搜索