JNI|在子线程中获得JNIEnv|AttachCurrentThread

    A JNI interface pointer (JNIEnv*) is passed as an argument for each native function mapped to a Java method, allowing for interaction with the JNI environment within the native method.This JNI interface pointer can be stored, but remains valid only in the current thread. Other threads must first call AttachCurrentThread()to attach themselves to the VM and obtain a JNI interface pointer. Once attached, a native thread works like a regular Java thread running within a native method. The native thread remains attached to the VM until it callsDetachCurrentThread() to detach itself.[3]

[cpp]  view plain copy
  1. void Call_Back_Invoke( void *user,int notify_id, unsigned int param )  
  2. {  
  3.     bool  isAttacked = false;  
  4.     JNIEnv* env;  
  5.     if(NULL == jni_tmpc.g_JVM)  
  6.     {  
  7.         LOGE("g_JVM == NULL");  
  8.         return ;  
  9.     }  
  10.     int status = (jni_tmpc.g_JVM)->GetEnv((void **) &env, jni_tmpc.g_JNI_VERSION);  
  11.   
  12.     if(status < 0) {  
  13.         LOGD("callback_handler:failed to get JNI environment assuming native thread");   
  14.         status = jni_tmpc.g_JVM->AttachCurrentThread(&env, NULL);  
  15.         if(status < 0) {  
  16.            LOGE("callback_handler: failed to attach current thread");  
  17.             return;  
  18.         }  
  19.         isAttacked = true;  
  20.     }  
  21.   
  22.     switch( notify_id )  
  23.     {  
  24.     case...  
  25.          ...  
  26.     }     
  27.     if(isAttacked)   
  28.     {  
  29.         (jni_tmpc.g_JVM)->DetachCurrentThread();  
  30.     }     
  31.     LOGE("jni Call_Back_Invoke(1) notify_id = %d",notify_id );  
  32. }  
转自  http://blog.csdn.net/stefzeus/article/details/6792518

你可能感兴趣的:(android)