本文内容参考多位大神的截图和代码。只是总结一下,可以更快的配置好。
一. 配置环境安装 NDK。
https://developer.android.com/ndk/downloads/index.html
新建一个类,声明native方法。这个类是java与C/C++交互的中介,方法由java声明,由C/C++实现。
三.打开android studio终端,使用javac编译上述文件,生成class文件。
然后在java目录使用 javah -jni 包名.类名 命令生成.h头文件然后就能看到生成了一个h文件。
新建一个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
。创建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} )
右键app,点击Link C++ Project with Gradle,选择path:刚才的CMakeLists.txt,它会在 App build 生成相应的代码。
六. make projext 大功告成。
七. so文件在本项目里的使用。
sourceSets { main() { jniLibs.srcDirs = ['src/main/libs'] jni.srcDirs = [] //屏蔽掉默认的jni编译生成过程 } }
文章来源: https://blog.csdn.net/qq_24143647/article/details/89642794