以cmake的形式开发:
1、配置ndk路径;
2、配置builde.gradle
##静态注册
3、建立native调用文件
public class NativeCall {
static {
System.loadLibrary("JNIHello");
}
public static native String hello();
}
Java调用代码示例:
textView.setText(NativeCall.hello());
4、进入相应的目录,生成头文件(terminal命令控制台中):
E:\flutterdemo\Jnidemo>cd app/src/main/java
E:\flutterdemo\Jnidemo\app\src\main\java>javah -d ../jni com.mysterycode.jnidemo.NativeCall(此处改为对应的包命+文件名)
5、新建对应的cpp文件,写对应的cpp文件(可以在Native调用文件方法上Alter+Enter):
#include <jni.h>
#include "com_mysterycode_jnidemo_NativeCall.h"
extern "C"
JNIEXPORT jstring JNICALL
Java_com_mysterycode_jnidemo_NativeCall_hello(JNIEnv *env, jclass type) {
return env->NewStringUTF("Hello from native.");
}
6、写对应的CMakeLists.txt
cmake_minimum_required(VERSION 3.6)
#jni中引入其他c/c++库(支持c++11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fexceptions -Wno-unused -Wno-gnu-alignof-expression -Wno-missing-field-initializers -std=c++11 -fvisibility=hidden -fexceptions -Wextra -Wno-unused-parameter -Wno-format-security -Wno-unused-local-typedef")
add_library( # Sets the name of the library.
JNIHello
SHARED #共享此库
com_mysterycode_jnidemo_NativeCall.cpp)
7、直接运行
目录参考:
参考:https://github.com/AndroidAdvanceWithGeektime/Chapter03
##动态注册(配置依然一样,但代码声明不同)
Java端代码:
static {
System.loadLibrary("native-lib");
}
public native void sayHello(String s);
Jni代码:
extern "C"
JNIEXPORT void JNICALL
native_sayHello(JNIEnv *env, jobject thiz,
jstring name) {
const char *j_name = env->GetStringUTFChars(name, NULL);
LOGD("动态注册:%s", j_name);
env->ReleaseStringUTFChars(name, j_name);
}
static const JNINativeMethod jniNativeMethod[] = {
{"sayHello", "(Ljava/lang/String;)V", (void *) (native_sayHello)}
};
/**
* 该函数定义在jni.h头文件中,System.loadLibrary()时会调用JNI_OnLoad()函数
*/
JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM *javaVm, void *pVoid) {
//通过虚拟机 创建全新的 env
JNIEnv *jniEnv = nullptr;
jint result = javaVm->GetEnv(reinterpret_cast<void **>(&jniEnv), JNI_VERSION_1_6);
if (result != JNI_OK) {
return JNI_ERR;
}
jclass dyactivity = jniEnv->FindClass(classPathName);
jniEnv->RegisterNatives(dyactivity, jniNativeMethod,
sizeof(jniNativeMethod) / sizeof(JNINativeMethod));
return JNI_VERSION_1_6;
}
github:https://github.com/Deep-In-It/JniDemo