1. Android studio创建Android工程
2. 项目右键 -> open module setting -> Install NDK
3. 设置NDK的环境变量
4. 创建调用Native的类
import android.util.Log;
public class NativeInterface {
static {
System.loadLibrary("NDK");
}
public native int add(int x, int y);
public void callNative() {
int ret = add(5, 6);
Log.i("csf", ret + "");
}
}
5. Build -> make project生成这个java文件的.class文件
6. javah ***生成.h文件,该文件用来编写C代码
7. 编写C代码,在app/src/main/java目录下新建jni目录,新建C文件JavaToC.c
#include <string.h>
#include <android/log.h>
#include <jni.h>
jint Java_com_example_samsung_nativetest_NativeInterface_add(JNIEnv* env, jobject thiz,
jint x,jint y)
{
return x+y;
}
8. 在jni目录下新建Android.mk文件
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_LDLIBS += -L$(SYSROOT)/usr/lib -llog
LOCAL_MODULE := NDK
LOCAL_SRC_FILES := \
JavaToC.c
include $(BUILD_SHARED_LIBRARY)
9. 在Terminal进入到jni目录,执行ndk-build命令,在app/src/main/java/libs目录会生成.so库文件
10. 添加build.gradle文件红色部分
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.example.samsung.nativetest"
minSdkVersion 24
targetSdkVersion 25
versionCode 1
versionName "1.0"
ndk {
moduleName "NDK"
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
jni.srcDirs = []
jniLibs.srcDirs 'src/main/libs'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}
11. 运行app