Android JNI Code callback Java problem
Problems with the call function cannot be found because of a multithreaded cause that could not find the Java class
Issue 1 The Java class is not found
Save it when you jni_onload.
Jniexport jint jnicall jni_onload (javavm* vm, void* reserved) {G_VM = VM; jnienv*Env= NULL; Jint result =-1;if(Vm->getenv (void**) &Env, jni_version_1_4)! = JNI_OK) {return-1; } assert (Env! = NULL); Register_location_methods (Env); result = Jni_version_1_4;returnResult;}intRegister_location_methods (jnienv*env) {jnienv =Env; Jclass Clazz; Clazz =Env->findclass ("Com/tongban/chat/netbilling");if(Clazz = = NULL) {return-1; } jnetbilling = Clazz; Onreceivedmsgtype =Env->getstaticmethodid (Clazz,"Onreceivedmsgtype","(I) V");//Env->callstaticvoidmethod (jnetbilling, Onreceivedmsgtype, 1); return 0;}
Issue 2 Multi-threaded callback call function
The jnienv generated here cannot obtain a global variable that is saved before the class function is required.
BOOL Isattacked= false; JNIEnv*Env int status=G_vm -GETENV ((void **)&env, jni_version_1_4);if(Status< 0) {Status=G_vm -Attachcurrentthread (&EnvNULL);if(Status< 0) {returnLen } isattacked= true; } env -Callstaticvoidmethod (Jnetbilling,onreceivedmsgtype,imsgtype);if(isattacked) {G_VM -Detachcurrentthread (); }
Output problem because still prefer cout Baidu a cout output to logcat log
int iMsgType = MSG_PACKET::GetMsgType(kBuffer); StreamBuf g_StreamBuf; std::cout.rdbuf(&g_StreamBuf); std::cout << iMsgType;//即可显示到logCat
#include <iostream>#include <streambuf>Class Streambuf: Publicstd::streambuf{enum{buffer_size =255, }; Public:Streambuf() {Buffer_[buffer_size] =' + '; SETP (Buffer_, Buffer_ + buffer_size-1); } ~streambuf () {sync (); }protected:VirtualInt_typeOverflow(Int_type c) {if(c! = EOF) {*pptr () = C; Pbump (1); } flush_buffer ();returnC }Virtual intSync () {flush_buffer ();return 0; }Private:int Flush_buffer() {intLen =int(Pptr ()-pbase ());if(Len <=0)return 0;if(Len <= buffer_size) Buffer_[len] =' + ';#ifdef ANDROIDAndroid_logpriority t = android_log_info; __android_log_write (T,"Jni_debug", Buffer_);#Else printf'%s ', Buffer_);#endif Pbump (-len);returnLen }Private:CharBuffer_[buffer_size + 1];};
Here we can finally interact with the android-> server->android
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Andorid NDK all kinds of pits and records.