New Module选择Android NativeLibrary生成一个Lib,自动配置好的externalNativeBuild脚本
defaultConfig {
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"
externalNativeBuild {
cmake {
cppFlags ""
}
}
}
externalNativeBuild {
cmake {
path "src/main/cpp/CMakeLists.txt"
version "3.10.2"
}
}
Java编写Native函数
public native String encJNI ( String src) ;
CPP编写native层实现
extern "C"
JNIEXPORT jstring JNICALL
Java_com_lg_encnativelib_NativeLib_encJNI ( JNIEnv * env, jobject thiz, jstring src) {
const char * name = env-> GetStringUTFChars ( src, NULL ) ;
std:: string res = EncImpl :: doEnc ( name) ;
env-> ReleaseStringChars ( src, reinterpret_cast < const jchar * > ( name) ) ;
return env-> NewStringUTF ( res. c_str ( ) ) ;
}
添加新的cpp文件 在CMakeLists.txt中添加引用
add_library(
...
EncImpl.cpp )
添加目录下的所有的cpp文件
# 查找当前目录下的所有源文件
# 并将名称保存到 DIR_SRCS 变量
aux_source_directory(. DIR_SRCS)
add_library( # Sets the name of the library.
encnativelib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
#encnativelib.cpp
#EncImpl.cpp
${DIR_SRCS}
)
添加子目录的cpp文件
aux_source_directory(./third DIR_SRCS)
手把手教你如何在Android下进行JNI开发(入门) https://cloud.tencent.com/developer/article/1983561