比如 聊天服务器 是异步的,在子线程返回结果,如何通知java.

在初始化时,把jobject mthedid  save下来,注意保存是要NewGlobalRef(minfo.classID);这样作

用到了cocos2d-x的jnihelper文件 

jint JNI_OnLoad(JavaVM *vm, void *reserved)

{

    JniHelper::setJavaVM(vm);

    g_jvm=vm;

    return JNI_VERSION_1_4;

}保存 JavaVM

extern JavaVM *g_jvm;

jclass g_class;

jmethodID g_mid;

void callinit() {

 

JniMethodInfo minfo;

bool isHave = false;

isHave = JniHelper::getStaticMethodInfo(minfo,

"com/buniess/bmbuniess/service/CommMsgService", "handlerSendMsg",

"(ILjava/lang/String;)V");

 

if (isHave) {

g_mid=minfo.methodID;

g_class = minfo.env->NewGlobalRef(minfo.classID);

 

}

 

}

在子线程返回时调用

void callJava(int MSG, std::string str) {

 

JNIEnv **env;

jclass cls;

jmethodID mid;

if (g_jvm->AttachCurrentThread(env, 0) < 0) {

LOGD("%s: AttachCurrentThread() failed", __FUNCTION__);

}

 

mid = (*env)->GetStaticMethodID(g_class, "handlerSendMsg",

"(ILjava/lang/String;)V");

if (mid == NULL) {

LOGD("GetMethodID() Error.....");

goto error;

}

 

jstring jstr;

jstr= JniHelper::string2jstring(str);

 

(*env)->CallStaticVoidMethod(g_class, g_mid, MSG, jstr);

 

error: if (g_jvm->DetachCurrentThread() != JNI_OK) {

LOGD("%s: DetachCurrentThread() failed", __FUNCTION__);

}

}

这样就可以完成c++异步和java通信了

相关文章:

  • 2021-11-30
  • 2021-10-19
  • 2022-02-14
  • 2021-11-30
  • 2021-11-30
  • 2021-06-28
猜你喜欢
  • 2021-04-11
  • 2022-12-23
  • 2021-05-24
  • 2022-01-28
  • 2021-07-14
  • 2021-10-02
  • 2022-12-23
相关资源
相似解决方案