首页  编辑  

Android安卓中JNI中调用其他so库

Tags: /Android/   Date Created:
安卓当中,使用cmake调用jni,并且在c代码中调用其他的so库,该如何做?
例如你的工程中调用一个so,这个so文件调用海康的sdk的so文件,该如何去做?

1. 请新建一个工程,并带C++支持
2. 打开CMakeLists.txt文件,在find_library()后面,添加类似的代码:
add_library( hcnetsdk SHARED IMPORTED )
set_target_properties(hcnetsdk  PROPERTIES IMPORTED_LOCATION
你硬盘上的目录,例如D:/abc/hksdk/${ANDROID_ABI}/libhcnetsdk.so)
然后修改target_link_libraries,在末尾添加hcnetsdk,类似下面:
target_link_libraries( # Specifies the target library.
                       native-lib

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib}
                       hcnetsdk)
完整cmakelists.txt如下:
cmake_minimum_required(VERSION 3.4.1)

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).
             src/main/cpp/native-lib.cpp )

add_library( hcnetsdk SHARED IMPORTED )
set_target_properties(hcnetsdk  PROPERTIES IMPORTED_LOCATION
		C:/Users/user/Desktop/demo/app/libs/${ANDROID_ABI}/libhcnetsdk.so)

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}
                       hcnetsdk)
3. 修改app目录下的build.gradle文件,在android/defaultConfig中添加下面的代码:
sourceSets {
    main {
        // Don't use native sources building using gradle,
        // since gradle ignores custom Android.mk
        jni.srcDirs = []
        jniLibs.srcDirs = ['libs']
    }
}
如果你只需要某个平台的编译库,可以在externalNativeBuild中修改如下(例如只编译armeabi-v7a平台):
externalNativeBuild {
    cmake {
        cppFlags ""
        abiFilters "armeabi-v7a"
    }
}
4. 在你的CPP文件中,可以正常调用海康的SDK代码了,当然你得在最开头 #include "HCNetSDK.h" ,记得把海康的库文件,复制到app目录下的libs目录中,记得带cpu架构目录结构,如armeabi-v7a,这个目录下才是libhcnetsdk.so等文件,需要把海康所有的so文件都复制过去。