android 添加模块并使用JNI调用c++

首先新建一个模块,比如Android Library。在该模块的java类中,首先载入c++的共享库,语句如下:

static{
      System.loadLibrary("libname");
} 
//libname就是下面要建立的cpp文件的名称

后面声明使用JNI的java方法,比如
public native String stringFromJNI();
其中的native不可省略

完成后在该模块下src/main目录下新建cpp文件夹, 然后在cpp文件夹下新建cpp文件(文件名要与java类中载入共享库的名称相同),实现该JNI方法。所对应的c++函数名形式为:

#include <jni.h> //必要语句

extern "C"
JNIEXPORT jstring JNICALL
Java_包名_类名_方法名(JNIEnv *env) 注:一般在写的时候AS会给出提示,建议直接使用提示生成。

cpp文件写完后, 再在该文件夹下新建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.
             libname

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             src/main/cpp/libname.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.

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.
                       libname

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

然后再在该模块下的build.gradle中添加对c++的编译配置信息。在defaultConfig节点下,添加

externalNativeBuild {
    cmake {
        cppFlags "-fexceptions"
        arguments "-DANDROID_STL=c++_shared"
    }
    ndk{
        abiFilters 'armeabi-v7a', 'arm64-v8a' ,'x86'
    }
}

作用是配置为共享库,与设置目标平台。接着再将CMakeLists.txt关联到模块,在android节点下添加

externalNativeBuild {
    cmake {
        path "src/main/cpp/CMakeLists.txt"
    }
}

至此模块的任务算是完成了。可以在其它模块中引入该模块使用。引入方式为:
import 该模块包名.模块类名;
另外要在其模块的build.gradle中,dependencies节点中,添加

implementation project(‘:模块名’)