Android JNI开发:从 传统的ndk-build 转成 CMake编译 JNI代码

修改步骤:

  1. 修改Gradle,增加对CMake的支持
  2. 修改src/main/jni为src/main/cpp
  3. 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})
发布了33 篇原创文章 · 获赞 5 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/hjiangshujing/article/details/104502947