Android打包原生代码到aar并提供给第三方使用

1.Library Module配置

1.新建Module并将id设置为

com.android.library

2.在build.gradle中android block内部添加prefab发布功能(此功能主要是生成CMake config文件供第三方通过find_package()函数直接导入使用)
buildFeatures {
        prefabPublishing true
}
3.在build.gradle的android block中添加如下原生库信息(库名称以及库头文件)
prefab {
        storkpostprocessor {
            headers "src/main/cpp/include"
        }
    }
4.一个示例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'

构建的aar文件位于build---outputs

2.使用者

1.在build.gradle android block下添加如下代码
buildFeatures {
        prefab true
    }
2.添加aar依赖

将上面生成的aar文件放入lib文件夹下,同时在build.gradle的dependencies block下添加如下代码:

implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')

此时,aar就会被当前模块依赖,但是要在本地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的名称,其次在下面链接代码的时候,格式是

module名称::lib名称

还有需要注意的点是:

在你提供的头文件接口给第三方使用之前,函数涉及的参数类型或返回类型,最好不要使用依赖库中的第三方类型,最好使用原始数据类型

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容