java.lang.RuntimeException:无法在未调用Looper.prepare()的线程内创建处理程序

时间:2014-06-22 14:48:27

标签: java java-native-interface cocos2d-x

当我尝试从JNI调用java类中的非静态方法时,我遇到异常。我得到的例外是:

无法在未调用Looper.prepare()

的线程内创建处理程序

这是我的JNI呼叫代码:

jclass mClass = env->FindClass("com/secrethq/match3/Match3Activity");

jmethodID constructor = env->GetMethodID( mClass, "<init>", "()V");
CCLog("jClass Located?");

jobject object = env->NewObject(mClass, constructor);
mid = env->GetMethodID(mClass, "onClickPostStatusUpdate", "(I)V");


CCLog("mID: %d", mid);

if (mid!=0)
env->CallVoidMethod(mClass, mid, object, score);
        //-----------------------------------------------------------
CCLog("Finish");
if(isAttached)
    jvm->DetachCurrentThread();

这是我在java类中的方法:

private void onClickPostStatusUpdate(int score) {
    System.out.println("Match3Activity.onClickPostStatusUpdate()");
    performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
}

这是Logcat输出:

06-22 20:20:39.342: E/AndroidRuntime(14899): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
06-22 20:20:39.342: E/AndroidRuntime(14899):    at android.os.Handler.<init>(Handler.java:121)
06-22 20:20:39.342: E/AndroidRuntime(14899):    at android.app.Activity.<init>(Activity.java:772)
06-22 20:20:39.342: E/AndroidRuntime(14899):    at org.cocos2dx.lib.Cocos2dxActivity.<init>(Cocos2dxActivity.java:37)
06-22 20:20:39.342: E/AndroidRuntime(14899):    at com.secrethq.match3.Match3Activity.<init>(Match3Activity.java:45)
06-22 20:20:39.342: E/AndroidRuntime(14899):    at org.cocos2dx.lib.Cocos2dxRenderer.nativeTouchesEnd(Native Method)
06-22 20:20:39.342: E/AndroidRuntime(14899):    at    org.cocos2dx.lib.Cocos2dxRenderer.handleActionUp(Cocos2dxRenderer.java:129)
06-22 20:20:39.342: E/AndroidRuntime(14899):    at     org.cocos2dx.lib.Cocos2dxGLSurfaceView$9.run(Cocos2dxGLSurfaceView.java:258)
06-22 20:20:39.342: E/AndroidRuntime(14899):    at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1462) 
06-22 20:20:39.342: E/AndroidRuntime(14899):    at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)

1 个答案:

答案 0 :(得分:0)

该行:

jobject object = env->NewObject(mClass, constructor);

尝试实例化一个Activity。通常,您不应该手动实例化活动,而是要使用指定的Android API创建它们,例如Context.startActivity

通过规避API,您已经陷入了在不支持创建活动的线程中创建活动的情况。

这是导致错误的原因。但是:你可能想重新考虑代码作为一个整体。不确定你要做什么,但看起来你使用的模式并不合适。