首先安装必要的SDK Tools(LLDB、CMake和NDK)
打开Android Studio----Tools----SDK Manager
如下图所示,在右侧的页面中选择SDK Tools勾选LLDB、CMake和NDK进行下载安装
然后在已有项目中需要NDK编译的Module文件夹中创建CMakeLists.txt,文件内的代码如下:
make_minimum_required(VERSION 3.6)
add_library( # Sets the name of the library.
XJni
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/jni/XJni.c )
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log )
target_link_libraries( # Specifies the target library.
XJni
# Links the target library to the log library
# included in the NDK.
${log-lib} )
在project中右键点击需要NDK编译的Module文件夹,选择“Link C++ project with gradle”
在弹出的提示框中选择刚新建配置的CMakeLists.txt文件,点击OK
该module的build.gradle文件如下:
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.learnndk"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
//非系统自动生成,非必须,选择配置
externalNativeBuild{
cmake{
cppFlags ""
//生成多个版本的so文件
abiFilters 'arm64-v8a','armeabi-v7a','x86','x86_64'
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
//非自动生成,必须,否则后面的步骤中不会弹出Create Function
sourceSets{
main{
jni.srcDirs = ['src/main/jni','src/main/jni/']
}
}
//系统自动生成,必须
externalNativeBuild {
cmake {
path file('CMakeLists.txt')
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
此时,编译的时候会报错,找不到XJni.c文件,我们去到/app/src/main/jni/目录下创建XJni.c文件
输入一行代码
#include <jni.h>
此时再编译就不会报错了。
接下来创建XJni.java来调用XJni.c
package com.example.learnndk;
public class XJni {
static {
System.loadLibrary("XJni");
}
public native String getStr(String s);
}
getStr方法显示错误红色 ,选中函数名,alt+enter,
选择create function后,函数就自动在XJni.c文件中生成了。
#include <jni.h>
JNIEXPORT jstring JNICALL
Java_com_example_learnndk_XJni_getStr(JNIEnv *env, jobject instance, jstring s_) {
const char *s = (*env)->GetStringUTFChars(env, s_, 0);
// TODO
(*env)->ReleaseStringUTFChars(env, s_, s);
return (*env)->NewStringUTF(env, returnValue);
}
我们修改returnValue为固定字符
return (*env)->NewStringUTF(env, “Hello JNI”);
最后测试一下是否能正常调用
XJni xJni = new XJni();
String result = xJni.getStr("");
得到result的结果为Hello JNI,调用成功。