1.Library Module配置
1.新建Module并將id設(shè)置為
com.android.library
2.在build.gradle中android block內(nèi)部添加prefab發(fā)布功能(此功能主要是生成CMake config文件供第三方通過find_package()函數(shù)直接導(dǎo)入使用)
buildFeatures {
prefabPublishing true
}
3.在build.gradle的android block中添加如下原生庫信息(庫名稱以及庫頭文件)
prefab {
storkpostprocessor {
headers "src/main/cpp/include"
}
}
4.一個(gè)示例CMakeLists.txt文件
# Sets the minimum version of CMake required to build your native library.
# This ensures that a certain set of CMake features is available to
# your build.
cmake_minimum_required(VERSION 3.4.1)
#project(postprocessor-stork)
# Specifies a library name, specifies whether the library is STATIC or
# SHARED, and provides relative paths to the source code. You can
# define multiple libraries by adding multiple add_library() commands,
# and CMake builds them for you. When you build your app, Gradle
# automatically packages shared libraries with your APK.
find_package(OpenCV 4.8 REQUIRED java)
message("opencv_libraries name = ${OpenCV_LIBRARIES}")
add_library( # Specifies the name of the library.
storkpostprocessor
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/cpp/PostProcessor.cpp )
# Specifies a path to native header files.
include_directories(src/main/cpp/include/)
target_link_libraries(
storkpostprocessor
${OpenCV_LIBRARIES}
)
5.打包aar文件
Build菜單---Make Module 'Your Module Name'
構(gòu)建的aar文件位于build---outputs
2.使用者
1.在build.gradle android block下添加如下代碼
buildFeatures {
prefab true
}
2.添加aar依賴
將上面生成的aar文件放入lib文件夾下,同時(shí)在build.gradle的dependencies block下添加如下代碼:
implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')
此時(shí)弟塞,aar就會(huì)被當(dāng)前模塊依賴卷谈,但是要在本地c++代碼中使用葵蒂,還需要配置CMake,還記得我們上面說的CMake的config mode嗎畜普?
3.CMakeLists.txt中依賴aar中的原生庫
find_package(YourLibraryProjectName REQUIRED CONFIG)
target_link_libraries( # Specifies the target library.
postprocessor
YourLibraryProjectName::YourLibraryName
# Links the target library to the log library
# included in the NDK.
${log-lib})
這里需要注意一下,YourLibraryProjectName是上面生成aar的工程名稱,通常是module的名稱畜隶,其次在下面鏈接代碼的時(shí)候,格式是
module名稱::lib名稱
還有需要注意的點(diǎn)是:
在你提供的頭文件接口給第三方使用之前号胚,函數(shù)涉及的參數(shù)類型或返回類型籽慢,最好不要使用依賴庫中的第三方類型,最好使用原始數(shù)據(jù)類型