Android:CallStaticVoidMethod只被调用一次

时间:2013-12-13 21:21:57

标签: java android java-native-interface

我有一个JNI代码,我试图用Java调用静态方法。

JNI中的OnLoad如下所示

extern "C" jint JNI_OnLoad(JavaVM *jvm, void *reserved) {
        JNIEnv *e;

        mJvm = jvm;

        if (jvm->GetEnv((void**) &e, JNI_VERSION_1_4) != JNI_OK) {
                ALOGE("Error getting Env var");
                return JNI_ERR;
        }

        ALOG_ASSERT(env, "Could not retrieve the env!");

        app = e->FindClass("xyz");
        updateService = e->GetStaticMethodID(app, "updatestatus", "(I)V");

        jniRegisterNativeMethods(e, "xyz",
                                 Methods, NELEM(Methods));

        return JNI_VERSION_1_4;
}

我有以下全局变量

JavaVM *mJvm;
jclass app;
jmethodID updateHDToService;

我试图调用Java方法的回调看起来像这样

JNIEnv *e;
if (!mIsListenerAttached) {
        if (mJvm->AttachCurrentThread(&e, NULL) != JNI_OK) {
                ALOGE("Error attaching native thread to java");
                mIsListenerAttached = false;
                return;
        }
        ALOGI("Aattached native thread to java");
        mIsListenerAttached = true;
}

e->CallStaticVoidMethod(app, updateHDToService, radioContext->signalStat);

Java中的静态方法只成功调用一次。下次执行相同的回调时,它不会调用java方法。

我在做什么wronG?

1 个答案:

答案 0 :(得分:0)

请查看http://developer.android.com/training/articles/perf-jni.html。您不需要保护变量 Calling AttachCurrentThread on an already-attached thread is a no-op.

但是不要忘记在本机线程退出之前调用mJvm->detachCurrentThread()