程序猿学习

使用Android Studio进行NDK开发

2015-12-09  本文已影响2427人  果核果核

第一,创建一个新项目,并且新建一个类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);

}

第二,执行Build->Make Project

编译工程,生成.class文件,在这个目录下

/Users/littleghost/Documents/Android/Github/FirstJNI/app/build/intermediates/classes/debug/me/corer/firstjni

第三,使用命令行生成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

第四,在jni目录中,新建main.c文件,实现头文件定义的方法

第五,配置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的目录

修改build.gradle配置

这时,再执行"Build->Rebuild Project",就可以编译出so文件了,在以下目录

/Users/littleghost/Documents/Android/Github/FirstJNI/app/build/intermediates/ndk/debug

第六,调用

直接在MainActivity中调用getStringFromNative和getIntFromNative

上一篇 下一篇

猜你喜欢

热点阅读