需要三步:
1、在C++代码中实现JNI的各种方法
2、C++代码中注册到系统
3、在JAVA源码中声明
一、jni.h
关键结构体
typedef struct {
const char* name; //JNI函数的名称
const char* signature; //描述JNI函数的参数和返回值
void* fnPtr; //JNI函数对应的C语言的函数指针
} JNINativeMethod;
二、C++中声明
android_util_Log.cpp
static JNINativeMethod gMethods[] = {
{ "isLoggable", "(Ljava/lang/String;I)Z", (void*) android_util_Log_isLoggable },
{ "println_native", "(IILjava/lang/String;Ljava/lang/String;)I", (void*) android_util_Log_println_native },
};
在java里调用isLoggable()==C++里的android_util_Log_isLoggable()
三、C++中需系统注册:
int register_android_util_Log(JNIEnv* env)
{
jclass clazz = env->FindClass("android/util/Log");
levels.verbose = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "VERBOSE", "I"));
levels.debug = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "DEBUG", "I"));
levels.info = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "INFO", "I"));
levels.warn = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "WARN", "I"));
levels.error = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "ERROR", "I"));
levels.assert = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "ASSERT", "I"));
return AndroidRuntime::registerNativeMethods(env, "android/util/Log", gMethods, NELEM(gMethods));
}
四、JAVA中调用
public static native boolean isLoggable(String tag, int level);
用native声明