在我的上一篇博文中我已经介绍了传统的ndk开发方式,今天我就来说说Android studio最新的cmake方式开发。

准备的材料还是如上篇博文所说的一样,opencv的Android源码。

1.创建Android工程,如图:

android studio 2.x ndk开发二

android studio 2.x ndk开发二

创建好之后会下app下生成CMakeLists.txt文件,这个是用于配置c/c++代码编译的。还生成了native-lib.cpp文件,打开后发现里面写代码有提示,很友好。

2.将下载好的opencv的动态库文件copy到libs目录下

android studio 2.x ndk开发二


3.配置CMakeLists.txt文件

CMakeLists.txt:

# 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_minimum_required(VERSION 3.4.1)

set(OPENCV_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libs)

#include_directories(E:/sdk/ndk-bundle/sources/cxx-stl/llvm-libc++/include)
#add_library(
#            c++_shared
#            SHARED
#            IMPORTED )
#set_target_properties(
#                        c++_shared
#                        PROPERTIES IMPORTED_LOCATION
#                        E:/sdk/ndk-bundle/sources/cxx-stl/llvm-libc++/libs/${ANDROID_ABI}/c++_shared.so)

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


#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")

include_directories(src/main/cpp/include) #包含OpenCv的头文件目录
add_library( lib_opencv
             SHARED
             IMPORTED )
set_target_properties( lib_opencv
                       PROPERTIES IMPORTED_LOCATION
                       ${OPENCV_DIR}/${ANDROID_ABI}/libopencv_java3.so )
                       #包含libopencv_java3.so这个库  ${ANDROID_ABI}对应不同cpu

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.

target_link_libraries( # Specifies the target library.
                       native-lib lib_opencv

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

4.配置app下build.gradle文件

externalNativeBuild {
    cmake {
        abiFilters "armeabi"
        cppFlags "-frtti -fexceptions"
        //arguments "-DANDROID_STL=c++_shared"
    }
}
//如果动态库放入src/main/jniLibs下,则不需要设置该项
sourceSets{
    main{
        jniLibs.srcDirs=['libs']
    }
}

上面的项都配置好之后,就可以运行了

源码地址:http://download.csdn.net/download/jxgzycxyxhp/10103497


相关文章: