原创内容转载请附加出处
一、流程概述:
1)创建一个文件夹用于存放C/C++代码,一般命名为jni或者cpp。
2)在文件夹中创建CMakeList.txt文件,这个文件是cMake的配置文件。
3)在文件夹中创建第一个C++文件。
4)在CMakeList.txt 文件中配置刚才创建的C++文件。
5)在build.gradle中配置CMake的配置文件(CMakeLists.txt)。
6)在项目的java代码中加载库文件,使用java调用库函数。
二、创建一个文件夹,文件夹名自定义,一般创建在src目录下,名字一般为jni或者cpp。
三、在文件夹下创建CMake的配置文件CMakeList.txt,也可以在其他文件夹,由于之后的配置需要使用相对路径,如果不了解这配置建议在刚创建的文件夹下创建。
以下是配置文件的默认内容
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
# Sets the minimum version of CMake required to build the native library.
cmake_minimum_required(VERSION 3.4.1)
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
add_library( # Sets the name of the library.
#这里只是当前条配置的一个符号,库的文件名,在java中加载就是使用这个名字
native-lib
# Sets the library as a shared library.
#这里代表生成动态链接库,一般不需要改动
SHARED
# Provides a relative path to your source file(s).
#这个是之后需要创建的第一个cpp文件,这里使用的是相对路径名,是相对当前配置文件路径
#如果你之后创建的CPP文件名不同需要修改这一项,改成你创建的文件名。
native-lib.cpp )
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
#从指定文件夹加载库文件,无需修改
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 )
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
#将其他库链接成一个库方便加载,这个也无需修改
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib} )
四、文件夹中创建cpp文件。
五、按照第三步中配置文件中的提示将你创建的cpp文件配置到对应位置。
六、在build.gradle中添加配置文件。
方法一:点击对应的文件夹右键,选择link C++ Project with Gradle
方法二:在build.gradle中添加配置
android {
externalNativeBuild {
cmake {
//这里文件夹路径根据自己创建的文件夹修改
path file('src/main/cpp/CMakeLists.txt')
}
}
}
七、在java中加载链接库
//1)加载库函数
static {
//这里的native-lib是在CMakeLists.txt配置文件中add_library()配置的第一个参数
System.loadLibrary("native-lib");
}
//2)创建调用C++的函数
// 1、函数需要使用native修饰
// 2、函数没有函数体
// 3、如果之前的配置正确这里直接使用alt+enter就可以自动在创建的
// 第一个CPP文件中自动创建对应的函数
pubic native String getMessg();