Android Studio 2.2不会将第三方库打包到apk

ton*_*yye 10 android cmake android-studio

我使用Android Studio 2.2 cmake来构建本机代码,在本机代码中我调用了ffmpeg api,因此应该打包ffmpeg库.我CMakelists.txt的如下:

cmake_minimum_required(VERSION 3.4.1)
include_directories(libs/arm/include)
link_directories(libs/arm/lib/)

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).
             # Associated headers in the same location as their source
             # file are automatically included.
             src/main/cpp/native-lib.cpp )


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 )

target_link_libraries( # Specifies the target library.
                       native-lib

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )
add_library(avcodec-57 SHARED IMPORTED)
set_target_properties(avcodec-57 PROPERTIES IMPORTED_LOCATION C:/Users/tony/Desktop/MyApplication/app/libs/arm/lib/libavcodec-57.so)
target_link_libraries(native-lib avcodec-57)
target_link_libraries(native-lib avformat-57)

target_link_libraries(native-lib avutil-55)
target_link_libraries(native-lib avfilter-6)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我可以成功创建项目,但是当我将apk安装到模拟器并运行时,它失败并显示找不到"libavcodec-57.so".然后我使用工具(分析apk)来检查apk,发现ffmpeg库没有打包.

wes*_*sel 3

我找到了一种适合我的方法,不确定它对你有帮助,但可能会。我正在使用 Android Studio 2.2,也遇到了你的问题。

我创建了一个 jar 文件,其中包含预构建的库:

lib
--|armeabi
--|--|libMyLIb.so
etc.
Run Code Online (Sandbox Code Playgroud)

只需在某处创建一个包含该内容的文件夹 lib,然后执行命令

zip -r myjar.zip lib && mv myjar.zip myjar.jar
Run Code Online (Sandbox Code Playgroud)

接下来,我将 jar 文件放在这里:

app/libs/myjar.jar
Run Code Online (Sandbox Code Playgroud)

并将这些行添加到 CMakeLists.txt,在 Android Studio 中构建本机 .so 库。也就是说,我从模板外的一个空项目开始,用于调用本机代码(默认的 libnative-lib.so):

# already there:
target_link_libraries( # Specifies the target library.
                   native-lib

                   # Links the target library to the log library
                   # included in the NDK.
                   ${log-lib} )

# my addition:
add_custom_command(TARGET native-lib POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy_directory
        "${PROJECT_SOURCE_DIR}/libs"
        $<TARGET_FILE_DIR:native-lib>)
Run Code Online (Sandbox Code Playgroud)

神奇的是,现在如果我构建 apk,我的 jar 的内容最终会出现在最终的 apk 中。不要问我为什么会这样,真的,我不知道,这是偶然的。

这对我来说意味着,我编译了空的 libnative-lib.so,其唯一目的是欺骗 Android Studio 包含我的 jar。

也许有人找到了一个更干净的解决方案,并且可以指出我的解决方案是一个荒谬的循环,是由于误解 gradle 和 cmake 而导致的......