publicclasslibrary_name{static{// if library .so is named 'libname.so'System.loadLibrary("name")}//跟Native註冊interface_name實體的Native function.privatenativeregisterInterfaceNameNative(interface_namevar1);//假設有一個叫做interface_name的 InterfacepublicInterfaceinterface_name{voidinterface_func(byte[]);}//java的接口,負責把interface_name的實體帶給Native function.publicvoidregisterInterfaceName(interface_namevar1){registerInterfaceNameNative(var1);}}
staticJavaVM*gJavaVM;jobjectcallback_obj;jmethodIDcallback_mid;JNIEXPORTjintJNICALLJava_com_XXXXX_library_name_somethingInitFunction(JNIEnv*env,jobjectobj){(*env)->GetJavaVM(env,&gJavaVM);}JNIEXPORTjintJNICALLJava_com_XXXXX_library_name_registerInterfaceNameNative(JNIEnv*env,jobjectobj,jobjectinstance){callback_obj=(*env)->NewGlobalRef(env,instance);jclassclz=(*env)->GetObjectClass(env,callback_obj);if(clz==NULL){//failed to find class}callback_mid=(*env)->GetMethodID(env,clz,"interface_func","([B)V");}// callback function in Cvoidcb_function(char*buf){JNIEnv*env;if((*gJavaVM)->AttachCurrentThread(gJavaVM,&env,NULL)!=JNI_OK){// attachCurrentThread() failed.}else{// create byte[]jbyteArrayarr=(*env)->NewByteArray(env,len);// set buf -> byte[](*env)->SetByteArrayRegion(env,arr,0,len,(jbyte*)buf);// call java function, which is implemented by user(*env)->CallVoidMethod(env,callback_obj,callback_mid,arr);}}
publicclassinterfaceImplimplementslibrary_name.interface_name{@Overridevoidinterface_func(byte[]a){// show new String(a);}}main{library_namelibrary=newlibrary_name();// call some function to init library// ...//這行最重要,要把implmenet完的實體送下去給Native層知道library.registerInterfaceName(newinterfaceImpl());...}