android5.1.1 jni代码,Android 向现有的项目添加JNI,调用C/C++代码(CMAKE方式)

1、先新建一个JNI目录,并新建一个cpp文件命名jniclass.cpp

2af92b19780c

image.png

2、在jni目录新建文件,命名为CMakeLists.txt

# Sets the minimum version of CMake required to build your native library.

# This ensures that a certain set of CMake features is available to

# your build.

#指定最小编译cmake的版本

cmake_minimum_required(VERSION 3.6.4)

# Specifies a library name, specifies whether the library is STATIC or

# SHARED, and provides relative paths to the source code. You can

# define multiple libraries by adding multiple add_library() commands,

# and CMake builds them for you. When you build your app, Gradle

# automatically packages shared libraries with your APK.

add_library(

#指定依赖库的名字

# Specifies the name of the library.

jniclass

# Sets the library as a shared library.

SHARED

# Provides a relative path to your source file(s).

jniclass.cpp

)

# Specifies a path to native header files.

include_directories(include/)

find_library( # Defines the name of the path variable that stores the

# location of the NDK library.

log-lib

# Specifies the name of the NDK library that

# CMake needs to locate.

log)

# Links your native library against one or more other native libraries.

target_link_libraries(

#同上面依赖库的名字

# Specifies the target library.

jniclass

# Links the log library to the target library.

${log-lib})

3、选择LinkC++ Project,选择CMakeLists.txt

2af92b19780c

image.png

4、在app或module的build.gradle添加

externalNativeBuild {

cmake {

...

version('3.10.2')

}

}

5、调用生成Jni的方法

static {

System.loadLibrary("jniclass");

}

public native String JniGetString();

报错按照提示生成方法

2af92b19780c

image.png

发现生成的是.c文件,并没有生成方法,可能Android Studio的问题,好,现在先修改.c文件包含在CMakeLists.txt,并同步项目,删除jniclass.c的内容,重新生成,发现已经生成了JNI方法。

2af92b19780c

image.png

把C文件内容复制到cpp中,然后再把CmakeLists.txt的路径修改成cpp文件,把.c文件删除,并同步工厂,发现cpp报红,按照提示修改

2af92b19780c

image.png

好然后以后生成的JNI方法都会在cpp文件生成了。

6、调用JNI方法获取字符串

2af92b19780c

image.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值