基础知识
1 什么是JNI?
JNI全称为:Java Native Interface。JNI 是本地编程接口,它使得在 Java 虚拟机内部运行的 Java 代码能够与用其它语言(如 C、C++)编写的代码进行交互
2 什么是NDK?
NDK全称是Native Development Kit,NDK提供了一系列的工具,帮助开发者快速开发C(或C++)的动态库,并能自动将so和java应用一起打包成apk。NDK集成了交叉编译器(交叉编译器需要UNIX或LINUX系统环境),并提供了相应的mk文件隔离CPU、平台、ABI等差异,开发人员只需要简单修改mk文件(指出“哪些文件需要编译”、“编译特性要求”等),就可以创建出so
工具安装
jni_install.png打开Android SDK 选中SDK Tools 勾选 LLDB CMake NDK 然后点击 下载-安装
JNI开发
新建一个jni moudle
jni01.png建一个java类
public class JNIEncrypt {
static {
System.loadLibrary("JNIEncrypt");
}
public static native int getJniTest();
}
生成.h文件
- 打开terminal 输入命令
cd core.jni/src/main/java
javah -jni org.ls.jni.JNIEncrypt(包名字+类名字)
编写cpp文件
- 新建一个jni目录与java目录同级将生成.h移动jni目录下
- 新建一个JNIEncrypt.cpp
//
// Created by Less on 2019/3/11.
//
#include <jni.h>
#include "org_ls_jni_JNIEncrypt.h"
extern "C" JNIEXPORT jint JNICALL Java_org_ls_jni_JNIEncrypt_getJniTest
(JNIEnv *, jclass) {
return 7777777;
}
CMakeLists.txt
将该文件建立在moudle目录下与moudle和build.gradle文件同级别
# 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.
JNIEncrypt
# Sets the library as a shared library.
SHARED
# (需要手动修改)Provides a relative path to your source file(s).
src/main/jni/JNIEncrypt.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.
# Main.so
#
# # Links the target library to the log library
# # included in the NDK.
# ${log-lib} )
上面的内容有几处需要修改 我已经标注
网友评论