如何在android的jni线程中实现回调

来源:互联网 发布:mac口红辩真假 编辑:程序博客网 时间:2024/05/17 06:12

JNI回调是指在c/c++代码中调用java函数,当在c/c++的线程中执行回调函数时,会导致回调失败。

其中一种在Android系统的解决方案是:

把c/c++中所有线程的创建,由pthread_create函数替换为由Java层的创建线程的函数AndroidRuntime::createJavaThread。


假设有c++函数:

[cpp] view plaincopy
  1. void *thread_entry(void *args)  
  2. {  
  3.     while(1)  
  4.     {  
  5.         printf("thread running...\n");  
  6.         sleep(1);  
  7.     }  
  8.       
  9.       
  10. }  
  11.   
  12. void init()  
  13. {     
  14.     pthread_t thread;  
  15.     pthread_create(&thread,NULL,thread_entry,(void *)NULL);  
  16. }  

init()函数创建一个线程,需要在该线程中调用java类Test的回调函数Receive:

[cpp] view plaincopy
  1. public void Receive(char buffer[],int length){  
  2.         String msg = new String(buffer);  
  3.         msg = "received from jni callback:" + msg;  
  4.         Log.d("Test", msg);  
  5. }  


首先在c++中定义回调函数指针:

[cpp] view plaincopy
  1. //test.h  
  2. #include <pthread.h>  
  3. //function type for receiving data from native  
  4. typedef void (*ReceiveCallback)(unsigned char *buf, int len);  
  5.   
  6. /** Callback for creating a thread that can call into the Java framework code. 
  7.  *  This must be used to create any threads that report events up to the framework. 
  8.  */  
  9. typedef pthread_t (* CreateThreadCallback)(const char* name, void (*start)(void *), void* arg);  
  10.   
  11. typedef struct{  
  12.     ReceiveCallback recv_cb;  
  13.     CreateThreadCallback create_thread_cb;  
  14. }Callback;  

再修改c++中的init和thread_entry函数:

[cpp] view plaincopy
  1. //test.c  
  2. #include <stdio.h>  
  3. #include <stdlib.h>  
  4. #include <pthread.h>  
  5. #include <sys/wait.h>  
  6. #include <unistd.h>  
  7. #include "test.h"  
  8.   
  9. void *thread_entry(void *args)  
  10. {  
  11.     char *str = "i'm happy now";  
  12.     Callback cb = NULL;  
  13.     int len;  
  14.     if(args != NULL){  
  15.         cb = (Callback *)args;    
  16.     }  
  17.       
  18.     len = strlen(str);  
  19.     while(1)  
  20.     {  
  21.         printf("thread running...\n");  
  22.         //invoke callback method to java  
  23.         if(cb != NULL && cb->recv_cb != NULL){  
  24.             cb->recv_cb((unsigned char*)str, len);  
  25.         }  
  26.         sleep(1);  
  27.     }  
  28.       
  29.       
  30. }  
  31.   
  32. void init(Callback *cb)  
  33. {     
  34.     pthread_t thread;  
  35.     //pthread_create(&thread,NULL,thread_entry,(void *)NULL);  
  36.     if(cb != NULL && cb->create_thread_cb != NULL)  
  37.     {  
  38.         cb->create_thread_cb("thread",thread_entry,(void *)cb);  
  39.     }  
  40. }  


然后在jni中实现回调函数,以及其他实现:

[cpp] view plaincopy
  1. //jni_test.c  
  2. #include <stdlib.h>  
  3. #include <malloc.h>  
  4. #include <jni.h>  
  5. #include <JNIHelp.h>  
  6. #include "android_runtime/AndroidRuntime.h"  
  7.   
  8. #include "test.h"  
  9. #define RADIO_PROVIDER_CLASS_NAME "com/tonny/Test"  
  10.   
  11.   
  12. using namespace android;  
  13.   
  14.   
  15. static jobject mCallbacksObj = NULL;  
  16. static jmethodID method_receive;  
  17.   
  18.   
  19.   
  20. static void checkAndClearExceptionFromCallback(JNIEnv* env, const char* methodName) {  
  21.     if (env->ExceptionCheck()) {  
  22.         LOGE("An exception was thrown by callback '%s'.", methodName);  
  23.         LOGE_EX(env);  
  24.         env->ExceptionClear();  
  25.     }  
  26. }  
  27.   
  28.   
  29.   
  30. static void receive_callback(unsigned char *buf, int len)  
  31. {  
  32.     int i;  
  33.     JNIEnv* env = AndroidRuntime::getJNIEnv();  
  34.     jcharArray array = env->NewCharArray(len);  
  35.     jchar *pArray ;  
  36.       
  37.     if(array == NULL){  
  38.         LOGE("receive_callback: NewCharArray error.");  
  39.         return;   
  40.     }  
  41.   
  42.     pArray = (jchar*)calloc(len, sizeof(jchar));  
  43.     if(pArray == NULL){  
  44.         LOGE("receive_callback: calloc error.");  
  45.         return;   
  46.     }  
  47.   
  48.     //copy buffer to jchar array  
  49.     for(i = 0; i < len; i++)  
  50.     {  
  51.         *(pArray + i) = *(buf + i);  
  52.     }  
  53.     //copy buffer to jcharArray  
  54.     env->SetCharArrayRegion(array,0,len,pArray);  
  55.     //invoke java callback method  
  56.     env->CallVoidMethod(mCallbacksObj, method_receive,array,len);  
  57.     //release resource  
  58.     env->DeleteLocalRef(array);  
  59.     free(pArray);  
  60.     pArray = NULL;  
  61.       
  62.     checkAndClearExceptionFromCallback(env, __FUNCTION__);  
  63. }  
  64.   
  65. static pthread_t create_thread_callback(const char* name, void (*start)(void *), void* arg)  
  66. {  
  67.     return (pthread_t)AndroidRuntime::createJavaThread(name, start, arg);  
  68. }  
  69.   
  70. static Callback mCallbacks = {  
  71.     receive_callback,  
  72.     create_thread_callback  
  73. };  
  74.   
  75.   
  76.   
  77. static void jni_class_init_native  
  78. (JNIEnv* env, jclass clazz)  
  79. {  
  80.     method_receive = env->GetMethodID(clazz, "Receive""([CI)V");  
  81. }  
  82.   
  83. static int jni_init  
  84. (JNIEnv *env, jobject obj)  
  85. {  
  86.   
  87.       
  88.     if (!mCallbacksObj)  
  89.         mCallbacksObj = env->NewGlobalRef(obj);  
  90.       
  91.     return init(&mCallbacks);  
  92. }  
  93.   
  94. static const JNINativeMethod gMethods[] = {    
  95.     { "class_init_native",          "()V",          (void *)jni_class_init_native },  
  96.     { "native_init",                "()I",          (void *)jni_init },  
  97. };    
  98.   
  99.   
  100.   
  101. static int registerMethods(JNIEnv* env) {    
  102.   
  103.   
  104.     const charconst kClassName = RADIO_PROVIDER_CLASS_NAME;  
  105.     jclass clazz;     
  106.     /* look up the class */    
  107.     clazz = env->FindClass(kClassName);    
  108.     if (clazz == NULL) {    
  109.         LOGE("Can't find class %s/n", kClassName);    
  110.         return -1;    
  111.     }    
  112.     /* register all the methods */    
  113.     if (env->RegisterNatives(clazz,gMethods,sizeof(gMethods)/sizeof(gMethods[0])) != JNI_OK)    
  114.     {    
  115.         LOGE("Failed registering methods for %s/n", kClassName);    
  116.         return -1;    
  117.     }    
  118.     /* fill out the rest of the ID cache */    
  119.     return 0;    
  120. }     
  121.   
  122.   
  123. jint JNI_OnLoad(JavaVM* vm, void* reserved) {   
  124.     JNIEnv* env = NULL;    
  125.     jint result = -1;    
  126.     LOGI("Radio JNI_OnLoad");    
  127.         if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {    
  128.         LOGE("ERROR: GetEnv failed/n");    
  129.         goto fail;    
  130.     }    
  131.   
  132.     if(env == NULL){  
  133.         goto fail;  
  134.     }  
  135.     if (registerMethods(env) != 0) {   
  136.         LOGE("ERROR: PlatformLibrary native registration failed/n");    
  137.         goto fail;    
  138.     }    
  139.     /* success -- return valid version number */        
  140.     result = JNI_VERSION_1_4;    
  141. fail:    
  142.     return result;    
  143. }   

jni的Android.mk文件中共享库设置为:

[cpp] view plaincopy
  1. LOCAL_SHARED_LIBRARIES := liblog libcutils libandroid_runtime libnativehelper  

最后再实现Java中的Test类:

[java] view plaincopy
  1. //com.tonny.Test.java  
  2.   
  3. public class Test {  
  4.   
  5.     static{  
  6.         try {  
  7.             System.loadLibrary("test");  
  8.             class_init_native();  
  9.               
  10.         } catch(UnsatisfiedLinkError ule){  
  11.             System.err.println("WARNING: Could not load library libtest.so!");  
  12.         }  
  13.           
  14.     }  
  15.       
  16.       
  17.   
  18.     public int initialize() {  
  19.         return native_init();  
  20.     }  
  21.   
  22.     public void Receive(char buffer[],int length){  
  23.         String msg = new String(buffer);  
  24.         msg = "received from jni callback" + msg;  
  25.         Log.d("Test", msg);  
  26.     }  
  27.       
  28.       
  29.       
  30.     protected  static native void class_init_native();  
  31.       
  32.     protected  native int native_init();  
  33.   
  34. }  

http://blog.csdn.net/xnwyd/article/details/7359925

0 0
原创粉丝点击