以下內(nèi)容均使用AndroidStudio開發(fā)
一、ndk環(huán)境配置
ndk下載:
http://developer.android.com/tools/sdk/ndk/index.html
選擇對應(yīng)的版本弄跌,下載解壓即可使用。
Paste_Image.png
Paste_Image.png
二唱星、建立ndkdemo
創(chuàng)建工程
Paste_Image.png
建立對應(yīng)的類,并增加靜態(tài)native方法跟磨,這里創(chuàng)建一個(gè)加法方法為例间聊。
生成.h文件
使用命令行生成java類對應(yīng)的頭文件
注意類名沒有.java后綴
javah -jni com.lib.ndk.MathUtil
在main目錄下生成jni文件夾
Paste_Image.png
把剛生成的.h文件拉到j(luò)ni目錄下,并實(shí)現(xiàn)相應(yīng)的.cpp
Paste_Image.png
.h文件:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_lib_ndk_MathUtil */
#ifndef _Included_com_lib_ndk_MathUtil
#define _Included_com_lib_ndk_MathUtil
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_lib_ndk_MathUtil
* Method: sum
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_com_lib_ndk_MathUtil_sum
(JNIEnv *, jclass, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
.cpp文件:
#include <com_lib_ndk_MathUtil.h>
JNIEXPORT jint JNICALL Java_com_lib_ndk_MathUtil_sum
(JNIEnv *env, jclass cls, jint a, jint b){
return a+b;
}
設(shè)置項(xiàng)目的build.gradle文件
設(shè)置jni名稱為:JniDemo抵拘,并生成各個(gè)架構(gòu)so
Paste_Image.png
在module中的gradle.properties(如無則創(chuàng)建)添加:
android.useDeprecatedNdk=true
編譯
Build->MakeProject
Paste_Image.png
使用
把so拷貝至需要使用項(xiàng)目中的jniLibs目錄下
在程序啟動(dòng)的同時(shí)調(diào)用
System.loadLibrary("JniDemo");//庫名
一般使用靜態(tài)自由塊保證在裝載的同時(shí)加載so庫
static {
System.loadLibrary("JniDemo");//庫名
}
在java層使用靜態(tài)方法調(diào)用即可:
MathUtil.sum(1,2);