1、创建接口文件
public class JniInterface {
native public String getStringFromJni();
}
2、build工程生成class文件,定位到class文件目录
命令行:
javah -jni com.test.ndk.JniInterface
生成 com.test.ndk.JniInterface.h 头文件,复制到src/main/jni目录下
3、复制.h头文件,改名为.c
/* DO NOT EDIT THIS FILE - it is machine generated */
#include "com_test_ndk_JniInterface.h"
/*
* Class: com_test_ndk_JniInterface
* Method: getStringFromJni
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_test_ndk_JniInterface_getStringFromJni
(JNIEnv * env,jobject obj)
{
return (*env)->NewStringUTF(env,"Hello From JNI22");
}
4、build/make project 即可生成so文件
ps:更改生成的so文件名
build.gradle中
defaultConfig {
applicationId "com.test.ndk"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
ndk{
moduleName "myLib"
}
}
5、使用
static {
System.loadLibrary("myLib");
}
PS:
ndk-build命令
cd /Users/user/AndroidStudioProjects/TestNDK/app/src/main/jni
jni user$ ndk-build
[armeabi] Compile thumb : myLib <= com_test_ndk_JniInterface.c
[armeabi] SharedLibrary : libmyLib.so
[armeabi] Install : libmyLib.so => libs/armeabi/libmyLib.so
打印log
build.gradle中
ndk{
moduleName "myLib"
ldLibs "log","z","m"
abiFilters "armeabi","armeabi-v7a","x86"
}
.c文件中
#include <android/log.h>
#define LOG_TAG "TestNDK"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
LOGD("%s","hahah");
参考:
http://ph0b.com/android-studio-gradle-and-ndk-integration/