我一直尝试从c ++调用java方法,我能够成功地使用Activity类但使用NativeActivity,它在调用CallVoidMethod时崩溃了。 GetMethodID能够找到它,它返回一个地址。环境与安全vm对象是有效的&从android_main()填充。是否有可能它不能用于本机活动类?
Cpp :(已编辑)
void SendNotification() {
JavaVM* lJavaVM = main_activity->vm;
JNIEnv* lJNIEnv = main_activity->env;
JavaVMAttachArgs lJavaVMAttachArgs;
lJavaVMAttachArgs.version = JNI_VERSION_1_6;
lJavaVMAttachArgs.name = "NativeThread";
lJavaVMAttachArgs.group = NULL;
jint lResult = lJavaVM->AttachCurrentThread(&lJNIEnv, &lJavaVMAttachArgs);
if (lResult == JNI_ERR)
return;
jobject lNativeActivity = main_activity->clazz;
jclass ClassNativeActivity = lJNIEnv->GetObjectClass(main_activity->clazz);
jmethodID _method = lJNIEnv->GetMethodID(ClassNativeActivity, "SendNotification", "()V");
lJNIEnv->CallVoidMethod(lNativeActivity, _method);
lJavaVM->DetachCurrentThread();
}
爪哇:
package com.thor.kalen;
import android.app.AlertDialog;
import android.app.NativeActivity;
import android.os.Bundle;
public class MainActivity extends NativeActivity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
} // End of public void onCreate(Bundle savedInstanceState)
public void SendNotification() {
new AlertDialog.Builder(this).setTitle("Alert").setMessage("").setNeutralButton("Close", null).show();
}
}
答案 0 :(得分:1)
com.thor.kalen.MainActivity.SendNotification()应为类 com.thor.kalen.MainActivity的 jobject 调用Java方法,而不是此对象的 jclass :它不是静态方法:
main_activity->env->CallVoidMethod(main_activity.clazz, _method)
请注意 native_activity.h 中的评论:
/** * The NativeActivity object handle. * * IMPORTANT NOTE: This member is mis-named. It should really be named * 'activity' instead of 'clazz', since it's a reference to the * NativeActivity instance created by the system for you. * * We unfortunately cannot change this without breaking NDK * source-compatibility. */ jobject clazz;
此外,您只能从主(UI)线程显示()一个AlertDialog。您的C ++代码建议您从后台线程执行此操作。
如果此代码在主线程上执行,则
main_activity->vm->DetachCurrentThread()
应该删除。 AttachThread()也可以删除,但在已经附加的线程上调用时,它是NOP。