1. JNI 加载SO库的时候,默认会调用接口 JNI_OnLoad,里面可以对函数接口进行注册,类似如下
void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) {
}
jint JNI_OnLoad(JavaVM* vm, void* reserved) {
JNIEnv* env = NULL;
jint result = -1;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
LOGE("ERROR: GetEnv failed\n");
goto bail;
}
assert(env != NULL);
if (registerNatives(env) != JNI_TRUE) {
LOGE("ERROR: registerNatives failed");
goto bail;
}
result = JNI_VERSION_1_4;
bail:
return result;
}
2.注册用注册接口 RegisterNatives
//static const char *gClassName = "jerome/com/usbcamera/CameraView";
static const char *gClassName = "jni/CameraView";
gClassName 要注册路径是否完全对应,否则加载会失败
static jint registerNativeMethods(JNIEnv* env, const char* className, JNINativeMethod* methods, int numMethods) {
jclass clazz;
clazz = env->FindClass(className);
if(env->ExceptionCheck()){
env->ExceptionDescribe();
env->ExceptionClear();
}
if (clazz == NULL) {
LOGE("Native registration unable to find class '%s'", className);
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, methods, numMethods) < 0) {
LOGE("RegisterNatives failed for '%s'", className);
return JNI_FALSE;
}
return JNI_TRUE;
}
3.对接口函数表注册,注意大小写和JAVA中的文件一致,否者LINK ERROR
static JNINativeMethod gMethods[] = {
{"nativePrepareCamera", "(IIII)I", (void *)native_prepare_camera},
{"nativeProcessCamera", "()I", (void *)native_process_camera},
{"nativePixelToYuv420sp","([B)V",(void *)native_pixel_to_yuv422sp},
{"nativeStopCamera", "()I", (void *)native_stop_camera},
{"nativePixelToBmp", "(Landroid/graphics/Bitmap;)V", (void *)native_pixel_to_bmp},
{"nativeStartRecord", "()I", (void *)native_start_record},
{"nativeStopRecord", "()I", (void *)native_stop_record},
};