JNI GetMethodID错误和指定项目中的崩溃

时间:2017-12-06 08:12:37

标签: android crash java-native-interface

对我来说有一个奇怪的问题。我试图通过本机代码调用Java函数。 它在项目A和B中工作正常,但总是在项目C中崩溃。错误信息是" AndroidRuntime:java.lang.NoSuchMethodError:no method ..."。 我检查了不同项目中的Java函数,它们完全相同。 这是我的Java代码:

package com.myproject;
public class LivePublisher{
static{
    System.loadLibrary("livepublisher");

    if (sInstance == null) {
        sInstance = new LivePublisher();
        //some other code
        sInstance.jniInit(MyApplication.instance);
    }
}

private void onEvent(int event, String msg) {
    if (mLivePublishDelegate != null) {
        mLivePublishDelegate.onEventCallback(event, msg);
    }
}

public interface LivePublishDelegate {

    public void onEventCallback(int event, String msg);

    public void onVideoData(byte[] data, int width, int height, int dataLen);

    public void onAudioData(byte[] data, int dataLen);
}

private native int jniInit(Object ctx);
}

这是我的原生代码:

#include <jni.h>
JavaVM *gs_jvm=NULL;
jobject gs_object=NULL;
void initcallback(JNIEnv* env,jobject obj);
void post_onEvent(int event, char* msg);

JNIEXPORT jint JNICALL Java_com_myproject_LivePublisher_jniInit(JNIEnv *env, jobject obj, jobject ctx){
    initcallback(env,obj);
}

void initcallback(JNIEnv* env, jobject obj)
{
    if(gs_jvm == NULL){
        env->GetJavaVM(&gs_jvm);
    }
    if(gs_object ==NULL){
        gs_object=env->NewGlobalRef(obj);
    }
}

void post_onEvent(int event, char* msg)
{
    JNIEnv *env;
    jclass clazz;
    jmethodID mtdId;
    int status;
    bool isAttached = false;

    status=gs_jvm->GetEnv((void**)&env,JNI_VERSION_1_6);
    LOGD("postevent getEnv");
    if(status <0){
        if(gs_jvm->AttachCurrentThread(&env,NULL) == JNI_OK){
            LOGD("postevent AttachedCurrentThread");
            isAttached = true;
        }else{
            LOGD("postevent AttachedCurrentThread false");
            return;
        }
     }

    clazz = env->GetObjectClass(gs_object);
    if(clazz == NULL){
        LOGD("postevent GetObjectClass error");
        if(isAttached){
            gs_jvm->DetachCurrentThread();
            LOGD("postevent detachcurrent");
        }
        return;
    }

    mtdId = env->GetMethodID(clazz,"onEvent","(ILjava/lang/String;)V");
    if(mtdId == NULL){
        LOGD("postevent GetMethodID error");
    }else{
        LOGD("postevent GetMethodID success");
        jstring jstr = env->NewStringUTF(msg);
        env->CallVoidMethod(gs_object,mtdId,event,jstr);
        LOGD("postevent callmethod");
    }

    if(isAttached){
        gs_jvm->DetachCurrentThread();
        LOGD("postevent detachcurrent");
    }
}

请帮帮我,谢谢~~~顺便说一下,它会打印一个日志&#34; postevent GetMethodID错误&#34;在项目C中,然后崩溃。

0 个答案:

没有答案