objective c 调用java,Objective C使用JNI调用Java方法

Can someone show me how to call a Java method from Objective C.

In more detail this is actually what I would like to do

1) Have first call from the java side to the objective C. during this call I would like to get a reference to the java object.

2) Later down the line I would like Objective C to use the reference got in the previous step to call Java methods.

Thanks

解决方案

The following seems to work. It is based on the above comment on following the C examples and this link.

As the link says do not create a global variable for the env instead create a global variable of the jvm, also create a global reference to your class.

Here is how I implement the step 1 :

"

1) Have first call from the java side to the objective C. during this call I would like to get a reference to the java object.

"

First declare global variable in the header file for

1) the jvm:

JavaVM *jvm;

2) The Java class:

jclass smartCallbackClass;

3) The java Object:

jobject smartCallbackObject;

Next in the call that comes from the Java side to the Objective C set the values for these variables

1) For the JVM:

(*env)->GetJavaVM(env, &jvm);

2) For the Object:

smartCallbackObject = (*env)->NewGlobalRef(env, obj);

3) For the Class:

if (smartCallbackClass == NULL) {

jclass localRefCls = (*env)->FindClass(env,"com/studyisland/nativelibs/smart/responsesdk/interfaces/thin/SMARTResponseThinClient");

if (localRefCls == NULL) {

NSLog(@"Unable to create a JNI Java Class reference \n");

}

//Create a global reference for JNI Java class

smartCallbackClass = (*env)->NewGlobalRef(env,localRefCls);

//Delete the local reference as it is no longer needed

(*env)->DeleteLocalRef(env, localRefCls);

//Is the global reference created successfully?

if (smartCallbackClass == NULL) {

NSLog(@"Unable to create JNI Java class reference \n");

return 0;

}

}

Here is the link from where I got the code for the class

Now the second step

"

2) Later down the line I would like Objective C to use the reference got in the previous step to call Java methods

"

To call from Objective C back to Java you need to make sure that the call is done on the same thread by which Java called Objective C, so here is the code.

-(void)classFailedToStop:(SMARTResponseCallBackEventArg*)anArg{

JNIEnv *env;

int attach = (*jvm)->AttachCurrentThread(jvm, (void**)&env, NULL);

if(attach == 0){

(*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_4);

jmethodID method = (*env)->GetMethodID(env, smartCallbackClass, "callback_onStopClassFailed", "()V");

(*env)->CallVoidMethod(env, smartCallbackObject, method);

}

(*jvm)->DetachCurrentThread(jvm);

}

Hope this helps.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值