本文内容参考多位大神的截图和代码。只是总结一下,可以更快的配置好。
一. 配置环境安装 NDK。
2. Android Studio里安装。菜单栏 Tools ----> SDK Manger ----> SDK TOOLS .查找 到NDK下载。
二. 打开AndroidStudio 新建一个类,声明native方法。这个类是java与C/C++交互的中介,方法由java声明,由C/C++实现。
三.打开android studio终端,使用javac编译上述文件,生成class文件。
1.终端 cd myJNI类所在的目录
2.使用javac编译上述文件. javac myJNI.java 生成 myJNI.class
3.cd 到项目里的java目录。然后在java目录使用 javah -jni 包名.类名 命令生成.h头文件 然后就能看到生成了一个h文件。 注意一定要在java层目录下输入命令,不然不会报错:找不到xxx类
四. 新建一个jni文件夹,新建test.c,把.h里面的内容复制进去,并实现里面的函数。
1. 新建一个jni文件夹
2.在jni文件夹下,新建test.c
3.把 ”javah -jni 包名.类名 命令生成.h头文件“ 生成的.文件放入jni文件夹下。并在test.c 实现它的方法。
4.接着在jni文件夹下新建Android.mk和Application.mk文件。
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := MyJni
LOCAL_SRC_FILES := Test.c
include $(BUILD_SHARED_LIBRARY)
APP_ABI := all
五. 使用CMake 。创建CMakeLists.txt文件
1.在Project 目录下,右键app,点击新建File文件,命名为CMakeLists.txt
2.配置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.
MyJni #.so库名 可自定义
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/jni/test.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.
MyJni #.so库名 可自定义
# Links the target library to the log library
# included in the NDK.
${log-lib} )
3.右键app,点击Link C++ Project with Gradle,选择path:刚才的CMakeLists.txt,它会在 App build 生成相应的代码。
六. make projext 大功告成。
七. so文件在本项目里的使用。
app Module 在Android 节点下:
sourceSets {
main() {
jniLibs.srcDirs = ['src/main/libs']
jni.srcDirs = [] //屏蔽掉默认的jni编译生成过程
}
}
标签:CMake,library,libraries,Mac,Studio,3.3,java,jni,Android
来源: https://blog.csdn.net/qq_24143647/article/details/89642794