文章目錄
Android Studio3.5JNI配置及使用
一、下載安裝NDK以及CMake
1.1進入SDK Manager
- 主頁右上角
File
->Settings
->Appearance & Behavior
->System Settings
->Android SDK
1.2開始下載
- 選中上方
SDK Tools
和下方的Show Package Details
多選框 - 選中需要下載的
NDK
版本以及CMake
版本,點擊右下角Apply
即可
安裝目錄會在上方sdk目錄中的ndk目錄中
二、新建項目
1.1新建Native C++
項目
1.2修改項目信息
1.3選擇C++版本
- 無特殊要求直接默認即可
1.4創建完成
cpp
目錄即爲c++
代碼目錄
二、配置CMake
2.1CMakeLists.txt
主配置文件
- 打開
app
目錄下的build.gradle
文件 path
:主配置文件相對路徑version
:版本號
externalNativeBuild {
cmake {
path "src/main/cpp/CMakeLists.txt"
version "3.10.2"
}
}
2.2CMakeLists.txt
詳解
2.2.1文件解析
# 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版本
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.
# 創建和命名庫,將其設置爲靜態或共享,並提供到其源代碼的相對路徑。
# 您可以定義多個庫,然後CMake爲您構建它們。Gradle自動將共享庫打包到你的APK中。
# 添加cpp文件到庫中
add_library( # Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
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.
# 將log庫儲存爲一個名爲log-lib的變量
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.
# 在上方定義好的native-lib庫中引入log庫
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib})
2.2.2添加多個.cpp
文件
add_library(
native-lib
SHARED
native-lib.cpp
one-lib.cpp
two-lib.cpp)
2.2.3生成多個.so
庫
- 在cpp目錄下新建文件夾,並在新建的文件夾下新建
CMakeLists.txt
文件
- 新建
.cpp
文件
one
目錄下CMakeLists.txt
文件內容
add_library(one-lib SHARED one-lib.cpp)
target_link_libraries(one-lib log)
two
目錄下CMakeLists.txt
文件內容
add_library(two-lib SHARED two-lib.cpp)
target_link_libraries(two-lib log)
- 在主配置文件下添加
add_subdirectory(one)
add_subdirectory(two)
參數傳入的是指定包含
CMakeLists
文件的目錄的相對路徑
- 點擊
Build
->Make Project
- 打開
app
->build
->intermediates
->cmake
->debug
->obj
中的任意文件夾
- 打開