1、安裝
下載NDK包後,放到與SDK同級的目錄下,並且配置好環境變數,配好後,在終端輸入ndk-build命令測試,出現如下情況,則代表安裝成功
Android NDK: Could not find application project directory ! Android NDK: Please define the NDK_PROJECT_PATH variable to point to it. /home/braincol/workspace/android/android-ndk-r5/build/core/build-local.mk:85: *** Android NDK: Aborting . Stop.
2、工程與代碼
a、建立android工程,編寫java代碼,寫好需要的本地方法,以及載入的c檔案名稱字
b、根據寫好的java代碼,產生.h的c檔案,其中產生.h檔案的步驟如下:
1、進入該項目的目錄下
braincol@ubuntu:~$ cd workspace/android/NDK/hello-jni/
2、ls查看工程檔案
braincol@ubuntu:~/workspace/android/NDK/hello-jni$ ls
AndroidManifest.xml assets bin default.properties gen res src
3、在工程目錄下建立一個jni檔案夾:
braincol@ubuntu:~/workspace/android/NDK/hello-jni$ mkdir jni
braincol@ubuntu:~/workspace/android/NDK/hello-jni$ ls
AndroidManifest.xml assets bin default.properties gen jni res src
4、執行如下語句就可以產生相應的.h檔案了:
braincol@ubuntu:~/workspace/android/NDK/hello-jni$ javah -classpath bin -d jni com.example.hellojni.HelloJni
c、根據b中產生好的.h檔案來編寫相應的.c檔案,根據自己的需要實現.h檔案中的方法
d、編寫Android.mk檔案,其格式為如下:
LOCAL_PATH := $(call my-dir)include $(CLEAR_VARS)LOCAL_MODULE := hello-jni //編譯的目標對象,系統將會產生 'libhello-jni.so'檔案,供java檔案調用LOCAL_SRC_FILES := hello-jni.c //編譯的源檔案,系統將根據該檔案來產生目標對象include $(BUILD_SHARED_LIBRARY)
e、產生.so共用庫檔案,在終端進入到該項目的目錄下,輸入ndk-build命令,即可在lib目錄下產生.so檔案,運行該項目,即可。
3、調試語句輸出
在 NDK 中, printf() 沒法輸出,所以我們需要藉助 log 庫來將我們 c 程式碼程式庫中需要輸出的內容,通過 java 控制台輸出。調用函數 __android_log_print(), 就可以在 Eclipse 中,查看 LogCat 來查看相關的輸出資訊了。
於是在c檔案的編寫中,需要引入android/log.h檔案:
#include <android/log.h>
同時聲明列印方法:
#define __android_log_print(......);例如:
#include <string.h>#include <stdio.h>#include <jni.h>#include <android/log.h>#define LOG_TAG "MYJNI"#define LOGI(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)static char s_string[] = "My god, I did it!";jstringJava_com_jpf_myjni_MyJNI_stringFromJNI( JNIEnv* env,jobject thiz ){ LOGI("MyJNI is called!"); return (*env)->NewStringUTF(env, s_string);}
因為列印是連結的log庫,所以在Android.mk檔案中加上如下一句:
LOCAL_LDLIBS += -llog
重新ndk-build,運行項目,可以在logcat中發現我們在c檔案中加的列印語句。
參考:
http://www.cnblogs.com/hibraincol/archive/2011/05/30/2063847.html
http://blog.csdn.net/xuxinyl/article/details/6409030