使用Android Studio进行NDK开发
第一,创建一个新项目,并且新建一个类FirstJNI
定义两个native接口getStringFromNative和getIntFromNative。
public class FirstJNI {
static{
System.loadLibrary("firstjni");//so 名称
}
public static native String getStringFromNative();
public static native int getIntFromNative(int a, int b);
}
![](https://img.haomeiwen.com/i168126/d5f8759ac775fed7.png)
第二,执行Build->Make Project
![](https://img.haomeiwen.com/i168126/9a31467da11c6092.png)
编译工程,生成.class文件,在这个目录下
/Users/littleghost/Documents/Android/Github/FirstJNI/app/build/intermediates/classes/debug/me/corer/firstjni
![](https://img.haomeiwen.com/i168126/f94a8bf79e11e02e.png)
第三,使用命令行生成c头文件
进到项目的app/src/main目录
CorerMacBook-Pro:~ littleghost$ cd /Users/littleghost/Documents/Android/Github/FirstJNI/app/src/main
执行javah命令
CorerMacBook-Pro:main littleghost$ javah -d jni -classpath /Users/littleghost/Documents/Android/SoftWare/sdk/platforms/android-16/android.jar:../../build/intermediates/classes/debug me.corer.firstjni.FirstJNI
这时候就会发现项目中多了一个jni目录,里面有一个.h文件me_corer_firstjni_FirstJNI.h
![](https://img.haomeiwen.com/i168126/76965a7b1e9b7889.png)
第四,在jni目录中,新建main.c文件,实现头文件定义的方法
![](https://img.haomeiwen.com/i168126/0911aa6538ea3454.png)
第五,配置ndk,生成so文件
到这里后,我们再执行一个"Build->Make Project",发现"Messages Gradle Build"会给出提示如下:
Error:Execution failed for task ':app:compileDebugNdk'.
> NDK not configured.
Download the NDK from http://developer.android.com/tools/sdk/ndk/.Then add ndk.dir=path/to/ndk in local.properties.
(On Windows, make sure you escape backslashes, e.g. C:\\ndk rather than C:\ndk)
这时候我们就应该先这里下载ndk,
然后在项目的local.properties配置ndk的目录
![](https://img.haomeiwen.com/i168126/e7ab259c1fb1ae6e.png)
修改build.gradle配置
![](https://img.haomeiwen.com/i168126/8500ccd0b6036e38.png)
这时,再执行"Build->Rebuild Project",就可以编译出so文件了,在以下目录
/Users/littleghost/Documents/Android/Github/FirstJNI/app/build/intermediates/ndk/debug
![](https://img.haomeiwen.com/i168126/55d036a22edd3cf5.png)
第六,调用
直接在MainActivity中调用getStringFromNative和getIntFromNative
![](https://img.haomeiwen.com/i168126/a6686cf482df6acb.png)
![](https://img.haomeiwen.com/i168126/a3aef7376d9975c4.png)