Android jni开发-2(在旧项目上添加支持cmake编译的jni)

在上篇文章介绍了怎么样去新建一个包含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 <jni.h>
#include <string>

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());
}



最后就是运行啦,上截图:




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值