Android-ndk开发(一)
一、开发环境:
1、Windows 10系统电脑
2、Android Studio 3.2.1
3、Jdk1.8
4、Android ndk 16 (开发JNI必备工具,就是模拟其他平台特性类编译代码的工具)
image.pngimage.png
二、新建项目,勾选支持C++选项,项目会自动构建支持原生开发,现在的版本使用Cmake构建,使用起来非常方便了。
image.png带有C/C++的项目目录多了CPP文件夹(存放C/C++代码的)和CMakeLists.txt文件(编译C/C++程序的)
image.png# 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.
#配置so库信息
add_library( # Sets the name of the library.
# 生成的so库名称,此处生成的so文件名称是libnative-lib.so
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
# 资源文件,可以多个,
# 资源路径是相对路径,相对于本CMakeLists.txt所在目录
src/main/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})
image.png
image.png
App目录下的build.gradle文件会新添配置Cmake环境的代码
image.png如果想要编译不同平台的so文件需要添加一下代码
ndk{
abiFilters "armeabi", "armeabi-v7a"//,"x86"
}
image.png
生成so文件的目录
image.png三、创建JNI方法。上面是创建项目勾选C/C++自动生成的一些配置和代码,下面我们自己定义一个Java本地接口(Jni)方法,在native-lib.cpp中执行逻辑。
1、在MainActivity中创建getJNIString()的JNI方法;
image.png当前状态方法状态还是红色,没有声明,现在我们根据提示在native-lib.cpp的类中创建。
image.png image.png我们便可以在这个方法执行我们想要处理的一些逻辑,这里需要使用JNI和C/C++语法。(仅供新手参考,正在学习中)
网友评论