本文操作环境:
win10/Android studio 3.2
1.环境配置
在SDK Tools里选择 CMAKE/LLDB/NDK点击OK 安装这些插件.
2.创建CMakeLists.txt文件
在Project 目录下,右键app,点击新建File文件,命名为CMakeLists.txt
点击OK,创建完毕!
3.配置文件
在CMakeLists.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.
test_lib #.so库名 可自定义
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/jni/test_lib.c ) #源文件所在目录
# 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.
test_lib #.so库名 可自定义
# Links the target library to the log library
# included in the NDK.
${log-lib} )
4.创建一个新的java类
在此类中添加代码
package com.example.administrator;
public class Test_lib {
static {
System.loadLibrary("test_lib");//加载.so库
}
public static native String getStr(String str);//调用C/C++接口函数
}
5.在main下面创建jni目录,创建test_lib.c文件,名字必须与CMakeLists.txt文件的源文件所在目录一致
6.右键app,点击Link C++ Project with Gradle
显示如下,选择CMakeLists.txt文件所在路径,点击ok,等待构建完成.
构建完成后,build.gradle文件会自动生成一些配置,如下图:
7.回到Test_lib.java文件,选中getStr()函数,按下Alt+Enter,点击Create function...,如下图。
此时会在test_lib.c文件里自动生成C/C++函数。接着就可以在.c文件里编写C/C++接口函数了。
然后Make Project成功后,会在如下目录生成.so文件.此时.so库生成成功,可随时调用了!
8.在其他java类中调用C/C++函数
在要调用的java类中导入Test_lib包:
在需要调用的地方进行调用
到此处就大功告成了!
初次使用CMake会觉得很繁琐,但是比传统的jni调用方式要方便很多,多用几次就会顺手了。
恕本人水平有限,如有错误还请不吝指出!
本文为作者原创,如需转载请注明出处!