比如 聊天服务器 是异步的,在子线程返回结果,如何通知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通信了