1.要生成头文件主要命令行
E:\project\android_jni_test>javah -jni -d E:\project\android_jni_test\app\src\main\jni -classpath "E:\project\android_jni_test\app\src\main\java" com.jni.test.MyJniUtils
-jni: 生成jni形式的头文件(默认值)
-d: 指定输出路径
-classpath: 指定类所在的根目录
com.test.ClassABC: 包名+类名
2.遇到找不到到类型,有可能是win10系统环境变量没有配置好 具体配置
CLASSPATH D:\android_studio\jdk1.8\lib
JAVA_HOME D:\android_studio\jdk1.8
Path 新建三个环境变量 D:\android_studio\jdk1.8 D:\android_studio\jdk1.8\jre\bin D:\android_studio\jdk1.8\bin
主要步骤:
1.写一个工具类,用户调用jni的方法,myJniLib为生成的so库的名称
public class JniUtils { static { System.loadLibrary("myJniLib"); } public static native String getName(); }
2.将工具类生成头文件,然后放在jni文件夹下,命令参照上面
3.实现jni方法,
#include "com_lib_jni_JniUtils.h" JNIEXPORT jstring JNICALL Java_com_lib_jni_JniUtils_getName (JNIEnv *env, jclass) { //如果是用C语言格式就用这种方式 // return (*env)->NewStringUTF(env,"Kiss dream"); //如果是用C语言格式就用这种方式 return env->NewStringUTF((char *) "test success"); }
4.build.gradle文件夹配置
android { defaultConfig { // 使用Cmake工具 externalNativeBuild { cmake { cppFlags "" abiFilters 'arm64-v8a','armeabi-v7a','x86','x86_64' } } } // 配置CMakeLists.txt路径 externalNativeBuild { cmake { path "CMakeLists.txt" // 设置所要编写的c源码位置,以及编译后so文件的名字 } } sourceSets { main { jni.srcDirs = ['src/main/jni', 'src/main/jni/'] } } }
5.把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. #CMakeLists.txt #指定需要CMake的最小版本 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. # 设置so文件名称. myJniLib # Sets the library as a shared library. SHARED # 设置这个so文件为共享. # Provides a relative path to your source file(s). # 设置这个so文件为共享. src/main/jni/com_lib_jni_JniUtils.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. # 制定目标库. myJniLib # Links the target library to the log library # included in the NDK. ${log-lib} )
6.clean project ,build完成!