准备工作
- 下载NDK
- 配置环境变量,在
~/.bash_profile文件下添加
1 2 3
| # 根据自己存放的位置指定 export NDK_ROOT=/Users/UserName/Documents/Android/android-ndk-r10 export PATH=$NDK_ROOT:$PATH
|
新建一个项目
创建一个MathKit类

1 2 3 4 5 6 7
| public class MathKit { public static native int square(int num);
static { System.loadLibrary("JniDemo"); } }
|
在命令行中进入目录,使用javah命令生成.h文件

将.h文件存放至jni文件夹下,并新建.cpp文件

根据头文件,编写cpp文件
1 2 3 4 5 6 7
| # include <com_zoe_ndkdemo_jni_MathKit.h>
JNIEXPORT jint JNICALL Java_com_zoe_ndkdemo_jni_MathKit_square (JNIEnv * env, jclass cls, jint num) { return num * num; }
|
在local.properties文件添加ndk路径
1
| ndk.dir=/Users/UserName/Documents/Android/android-ndk-r10
|
在app项目中的build.gradle中的defaultConfig中添加
1 2 3
| ndk { moduleName "JniDemo" }
|
之后就可以在代码中调用
1 2 3 4 5 6 7 8 9
| private TextView textView;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.text); textView.setText("2*2="+ MathKit.square(2)); }
|
示例:https://github.com/SeniorZhai/NdkDemo