Android Studio的配置ndk,jni的三种方法
gradle
在项目app下的build.gradle下面配置ndk:
在defaultConfig中插入ndk片段
ndk{
moduleName "testdemo1"
//生成的so名字
ldLibs "log","z","m"
abiFilters "armeabi","armeabi-v7a","x86"
//输出指定三种abi体系结构下的so库,目前可有可无。
}
android {
// .. android settings ..
sourceSets.main {
jni.srcDirs 'src/main/source'
}
}
//重新定义源文件位置,
sourceSets { main { jni.srcDirs = ['src/main/jni'] } }
cmake方法
把cmake.txt修改
添加自己源代码位置,如下,将add_library添加自己将要生成包名。添加源代码位置。target_link_libraries
add_library( # Sets the name of the library.
kuming2
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
# Associated headers in the same location as their source
# file are automatically included.
src/main/jni/main.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.
kuming2
# Links the target library to the log library
# included in the NDK.
${log-lib} )
相应源代码含义与相关配置,可参考下面两篇文章
代码解释非常靠谱
添加预编译库
然后在android{}最后添加如下语句,将CMakeLists.txt关联起来。
在模块app的局部build.gradle中,像之前一样添加好对应的语句:
defaultConfig{}中:
externalNativeBuild {
}
ndk {
abiFilters 'armeabi-v7a'
}
其中abiFilters的作用是,在生成.so库时,只生成对应结构的文件,以至于最后的.apk文件也只有对应架构的.so库。
然后在android{}中:
externalNativeBuild {
cmake {
path 'CMakeLists.txt'
}
}
sourceSets {
main {
jniLibs.srcDirs = ['../distribution/libs']
}
}