修改步驟:
- 修改Gradle,增加對CMake的支持
- 修改src/main/jni爲src/main/cpp
- rc/main/cpp增加CMakeLists.txt文件
修改Gradle,增加對CMake的支持
apply plugin: 'com.android.library'
apply from: 'publish.gradle'
apply from: './doc/quality/quality.gradle'
android {
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
minSdkVersion 23
targetSdkVersion 26
buildConfigField "String", "MVN_VERSION", '"' + "${mvn_version}" + '"'
ndk {
moduleName "lib-jni"
abiFilters "armeabi", "armeabi-v7a", "arm64-v8a"
}
}
//1. 增加對CMake的支持,指定CMakeLists文件路徑
externalNativeBuild {
cmake {
path 'src/main/cpp/CMakeLists.txt'
}
}
lintOptions {
checkReleaseBuilds false
abortOnError false
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
sourceSets.main {
jni.srcDirs = [] //disable automatic ndk-build call
jniLibs.srcDir 'src/main/libs'
}
}
dependencies {
implementation 'com.ted.contact.security:base-lib:0.9.5'
annotationProcessor 'com.ted.contact.security.annotation:string-encode:0.9.8'
}
- 註釋1處是在Gradle中增加的對CMake的支持
傳統的ndk-build 與 CMake目錄結構區別
- 以前的jni目錄改成cpp,位置不變
- 之前對C/C++文件的編譯配置Android.mk、Application.mk文件放在jni目錄下,現在改成CMakeLists.txt文件。(事實上這些文件的位置是可任意存放的,只需要在build.gradle配置好就行。)
如圖結構:
傳統的ndk-build 結構
CMake結構
CMakeLists.txt文件
cmake_minimum_required(VERSION 3.4.1)
# cmakelists 設置c++11 兼容armeabi
include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()
# cmakelists 設置c++11 兼容armeabi
# 編譯出一個動態庫 lib-jni,源文件只有 src/main/cpp/*.cpp *.c
file(GLOB_RECURSE ALL_SOURCE "*.cpp" "*.c")
add_library( # Sets the name of the library.
lib-jni
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
${ALL_SOURCE}
)
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
android)
target_link_libraries( # Specifies the target library.
lib-jni
android
# Links the target library to the log library
# included in the NDK.
${log-lib})