在现有AS项目中新增OpenCV|在现有AS项目中新增OpenCV c++库的支持

环境

  1. AS 3.4.1
  2. CMake 版本,AS上查不到,只显示了 installed.由 AS 安装
步骤
  1. AS 切换到 project 目录下
  2. 进入目录 app--src,右键 src,新建 Directory.命名为 cpp
  3. 右键 cpp文件夹,新建 cpp文件,命名为 test-cpp-lib.cpp
  4. 右键 cpp文件夹,新建 CMakeLists.txt 文件
  5. 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)# Creates and names a library, sets it as either STATIC # or SHARED, and provides the relative paths to its source code. # You can define multiple libraries, and CMake builds them for you. # Gradle automatically packages shared libraries with your APK.# 定义自己写的库 add_library( # Sets the name of the library. test-cpp-lib# Sets the library as a shared library. SHARED# Provides a relative path to your source file(s). test-cpp-lib.cpp)# Searches for a specified prebuilt library and stores the path as a # variable. Because CMake includes system libraries in the search path by # default, you only need to specify the name of the public NDK library # you want to add. CMake verifies that the library exists before # completing its build.# 如果需要其他NDK原生库的话,可自行在此处添加 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. test-cpp-lib# Links the target library to the log library # included in the NDK. ${log-lib})

CMake配置不在本文范围之内
  1. 进入 app 对应的 build.gradle,做以下操作
    • 在defaultconfig 块下新增
      externalNativeBuild { cmake { cppFlags "-std=c++14 -fexceptions -frtti" arguments "-DANDROID_ARM_NEON=TRUE",'-DANDROID_STL=c++_shared' // abi过滤 abiFilters 'armeabi-v7a','arm64-v8a' } } // abi过滤 ndk { abiFilters 'armeabi-v7a','arm64-v8a' }

  • 【在现有AS项目中新增OpenCV|在现有AS项目中新增OpenCV c++库的支持】在android块下新增
    // c/c++源码位置 sourceSets { main { jni.srcDirs = ['src/main/cpp'] jniLibs.srcDirs = ['src/main/jniLibs/libs'] } } externalNativeBuild { cmake { path "src/main/cpp/CMakeLists.txt" version "3.10.2" } }

  • 注意相应的路径,不要照抄。
  • 此时应该已经完成了 c++ 的接入配置,以下为验证手段。
验证
  1. 在src-main-java 文件夹内新建 java 文件,命名为 JNITools.java
package xyz.jimbray.demo; public class JNITools {static { System.loadLibrary("test-cpp-lib"); }public static native String getHelloString(); }

  1. 如果已经配置成功,AS现在会在 getHelloString 函数处提示错误,AS这个版本已经支持直接跳转到 cpp 文件新建对应函数。
  2. 但是我试的时候,出现直接跳转到一个 自动新建的 test-cpp-lib.c 文件,无视我自建的 cpp 文件,还报错。
  3. 我把 c 文件的内容直接复制到 cpp 文件,删除 c 文件,就可以了。
  4. 目前调用成功,不再用代码演示调用过程。
已发布至 我说的这句话是谎话

    推荐阅读