【问题标题】:Android JNI : The app crash when an object method is calledAndroid JNI:调用对象方法时应用程序崩溃
【发布时间】:2013-09-17 10:55:12
【问题描述】:

我在 Android 中使用 JNI 时遇到一个奇怪的问题。 我得到了我的 class SecureChannel 的对象方法 sendClearMessage(),我调用这个方法返回我的 class MessageResponse 的对象。这个对象被赋值给jobject,然后传递给CallObjectMethod来调用这个类的一个方法。每当我调用此类的方法时,应用程序都会在没有有用信息的情况下崩溃。我检查了每个获取 jmethodID 或 jclass 值的函数,因此问题不在于我获取此参数的方式。这是代码:

jobject sendMessage(char *ID , char *Message)
{
    jboolean isError;

    jmethodID SendClearMessage = NULL;
    jmethodID GetMessageResponseMethod = NULL;
    jmethodID IsErrorMethod = NULL;

    jobject ID_String = NULL;
    jobject Message_String = NULL;

    jbyte Length_Jbyte;

    jobject MessageResponse = NULL;
    jobject ResponseString = NULL;

    if(env == NULL || context == NULL) return NULL;

    if(SecureChannel == NULL)
    {
        SecureChannel = createSecureChannel(context);
    }

    if(SecureChannel == NULL)
    {
        return NULL;
    }

    ID_String = env->NewStringUTF(ID);
    Message_String = env->NewStringUTF(Message);

    SendClearMessage = getSecureChannelMethod("SendClearMessage" , "(Ljava/lang/String;Ljava/lang/String;)Lpkg/msg/MessageResponse;");

    if(SendClearMessage == NULL) return NULL;

    MessageResponse = env->CallObjectMethod(SecureChannel , SendClearMessage , ID_String , Message_String);

    //Check Exception throwing - DISABLED ever return true 
    /*
    if(env->ExceptionCheck() == true)
    {
        env->ExceptionDescribe();
        env->ExceptionClear();
        return NULL;
    }*/

    if(MessageResponse == NULL)
    {
        return NULL;
    }

    IsErrorMethod = getMessageResponseMethod("isError" , "()Z");

    if(IsErrorMethod == NULL) return NULL;

    isError = env->CallBooleanMethod(MessageResponse , IsErrorMethod); //Crash HERE

    if(isError == true) return NULL;

    GetMessageResponse = getMessageResponseMethod("getMessageResponse" , "()[B");

    if(GetMessageResponseMethod == NULL) return NULL;

    return env->CallObjectMethod(MessageResponse , GetMessageResponseMethod); //Crash HERE if I comment previous CallBooleanMethod
}

函数 getSecureChannelMethodgetMessageResponseMethod 是我编写的用于返回指定类的 jmethodID 的函数。 如果我在调用 sendClearMessage 方法后启用异常检查,我会得到一个真值,但在 Logcat 上我看不到任何异常。如果我评论 IsError 方法的调用,则会在调用另一个方法“GetMessageResponse”时发生崩溃。如果我评论这两种方法,应用程序不会崩溃,但我看不到以这种方式获取消息响应。

感谢任何帮助。

【问题讨论】:

  • 具体来说,显示调试器发出的本机崩溃的顶部(您不需要堆栈回溯之后的非常长的转储),以及紧接在它之前的一些日志。如果您看到“JNI 警告”之类的内容,则可能会指出您的问题所在。
  • 请将您的解决方案作为答案发布,以便您最终接受它并且问题似乎已解决,而不是继续弹出需要关注。

标签: java android c++ android-ndk java-native-interface


【解决方案1】:

问题如下:在 SendClearMessage 之前,必须检查 SecureChannel 的连接状态,因为连接是异步的。如果未检查连接,则调用该方法,但进一步调用其他对象会导致崩溃,可能是因为引发了未处理的异常。事实上,我已经读过只有在 VM 抛出异常时必须调用处理异常的方法:

http://developer.android.com/training/articles/perf-jni.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多