1.背景
android NDK可以用來編譯android的native方法,也可以將c和c++的代碼編譯成.so檔案,讓android程式運行。
2.NDK安裝(linux環境)
(1)下載對應的ndk版本,在shell裡輸入如下命令
gedit ~/.bashrc
(2)開啟bash檔案,添加下載的ndk路徑
NDKROOT=/home/CORPUSERS/28852262/android-ndk-r9c export PATH=$NDKROOT:$PATH
(3)輸入如下命令,然後重啟shell
source /etc/profile
(4)在shell中輸入ndk-build,出現如下狀態說明安裝成功
3.jni第一個demon helloworld
(1)編寫hello-jni.c檔案。
#include <string.h> #include <jni.h> /* This is a trivial JNI example where we use a native method * to return a new VM String. See the corresponding Java source * file located at: * * apps/samples/hello-jni/project/src/com/example/hellojni/HelloJni.java */ jstring Java_com_example_hellojni_HelloJni_aa( JNIEnv* env, jobject thiz ) { #if defined(__arm__) #if defined(__ARM_ARCH_7A__) #if defined(__ARM_NEON__) #define ABI "armeabi-v7a/NEON" #else #define ABI "armeabi-v7a" #endif #else #define ABI "armeabi" #endif #elif defined(__i386__) #define ABI "x86" #elif defined(__mips__) #define ABI "mips" #else #define ABI "unknown" #endif return (*env)->NewStringUTF(env, "Hello from JNI ! Compiled with ABI " ABI "."); }
這個c檔案實現輸出一個string型函數,注意這裡
Java_com_example_hellojni_HelloJni_aa
我們建立android應用的時候包和函數命名要和這個對應,否則彙報錯:native method is not found。如下圖
查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/