Android jni开发-2(在旧项目上添加支持cmake编译的jni)
程序员文章站
2022-06-23 11:59:04
在上篇文章介绍了怎么样去新建一个包含ndk的项目,那如果在旧项目上添加jni该怎么办呢?
1、在app/main文件夹下新建cpp文件夹,在cpp文件夹里面新建一个.cpp文件:...
在上篇文章介绍了怎么样去新建一个包含ndk的项目,那如果在旧项目上添加jni该怎么办呢?
1、在app/main文件夹下新建cpp文件夹,在cpp文件夹里面新建一个.cpp文件:
2、新建一个工具类:
public class JniUtil { static { System.loadLibrary("jni_lib"); } public native String getStringFromJni(); }3、在app目录下新建CMakeLists.txt文件:
cmake_minimum_required(VERSION 3.4.1) add_library( # Sets the name of the library. jni_lib # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). 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. jni_lib # Links the target library to the log library # included in the NDK. ${log-lib} )
(注意:CMakeLists.txt文件名区分大小写的;红框里面的jni_lib为第二步新建工具类里面的System.loadLibrary("jni_lib"),还有就是新建的cpp文件的路径)
4、在build.gradle里面添加配置:
externalNativeBuild { cmake { path "CMakeLists.txt" } }
5、最后编写.cpp文件,其实在做完上一步后,就可以在native方法下面按住Alt+Enter键去创建jni的方法了,代码如下:
#include #include extern "C" JNIEXPORT jstring JNICALL Java_com_sonic_jnidemo1_JniUtil_getStringFromJni(JNIEnv *env, jobject instance) { // TODO std::string hello = "欢迎来到C的世界!"; return env->NewStringUTF(hello.c_str()); }
最后就是运行啦,上截图: