#include <jni.h>
#include <string>
#include <android/log.h>
#define TAG "myDemo-jni" // 这个是自定义的LOG的标识
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG ,__VA_ARGS__) // 定义LOGD类型
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG ,__VA_ARGS__) // 定义LOGI类型
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG ,__VA_ARGS__) // 定义LOGW类型
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG ,__VA_ARGS__) // 定义LOGE类型
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,TAG ,__VA_ARGS__) // 定义LOGF类型
using namespace std;
static JavaVM *g_currentJVM = nullptr;
static jclass g_cls = nullptr;
static const char *classPathName = "android/app/mmkv/MMKV";
static int registerNativeMethods(JNIEnv *, jclass);
jstring stringJni(JNIEnv *env, jobject) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
extern "C" JNIEXPORT JNICALL jint JNI_OnLoad(JavaVM *vm, void *reserved) {
g_currentJVM = vm;
JNIEnv *env;
if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
if (g_cls) {
env->DeleteGlobalRef(g_cls);
}
jclass instance = env->FindClass(classPathName);
if (!instance) {
LOGE("fail to locate class: %s", classPathName);
return -2;
}
g_cls = reinterpret_cast<jclass>(env->NewGlobalRef(instance));
if (!g_cls) {
LOGE("fail to create global reference for %s", classPathName);
return -3;
}
int ret = registerNativeMethods(env, instance);
if (ret != 0) {
LOGE("fail to register native methods for class %s, ret = %d", classPathName, ret);
return -4;
}
return JNI_VERSION_1_6;
}
static JNINativeMethod g_method[] = {
{"stringJni", "()Ljava/lang/String;", (void *) stringJni}
};
static int registerNativeMethods(JNIEnv *env, jclass cls) {
return env->RegisterNatives(cls, g_method, sizeof(g_method) / sizeof(g_method[0]));
}
网友评论