Search code examples
androidandroid-ndkjava-native-interfacejnienv

JNI. different behavior between different Android OS versions


my application runs following code :

void BmrDeviceInfo_convertToC(JNIEnv *pEnv, jobject jBmrDeviceInfo, BmrDeviceInfo& cBmrDeviceInfo){

__android_log_print(ANDROID_LOG_INFO, "BEAMER_JNI", "g_classBmrDeviceInfo is = %s", (g_classBmrDeviceInfo == NULL) ? "NULL" : "OK"); //g_classBmrDeviceInfo is initialize on JNI_OnLoad

jfieldID fieldName = pEnv->GetFieldID(g_classBmrDeviceInfo, "m_strName", "Ljava/lang/String;"); // OK for Android 4.2 and crash for Android 3.1 or less

..................................
}

And LogCat output for crash case:

04-17 16:28:44.118: I/BEAMER_JNI(446): g_classBmrDeviceInfo is = OK
04-17 16:28:44.118: W/dalvikvm(446): JNI WARNING: 0x4053dc70 is not a valid JNI reference
04-17 16:28:44.118: W/dalvikvm(446):              in Lcom/xxxxxxx/xxxxxx/controller/CoreController;.Init (Lcom/xxxxxxx/xxxxxx/listviews/DeviceInfo;Ljava/lang/String;)I (GetFieldID)
04-17 16:28:44.118: I/dalvikvm(446): "main" prio=5 tid=1 RUNNABLE
04-17 16:28:44.118: I/dalvikvm(446):   | group="main" sCount=0 dsCount=0 obj=0x4001f1a8 self=0xce48
04-17 16:28:44.118: I/dalvikvm(446):   | sysTid=446 nice=0 sched=0/0 cgrp=default handle=-1345006528
04-17 16:28:44.118: I/dalvikvm(446):   | schedstat=( 276745040 468907344 84 )

Thanks for the help!


Solution

  • JNI functions that accept objects require local or global refs. Pre-ICS these were raw pointers, but in ICS that changed to a table index system.

    You don't say what version was used to generate the output in the question. The hex value 0x4053dc70 looks like a raw pointer, so I'm assuming this is pre-ICS. Looking at the error message, it appears that g_classBmrDeviceInfo is invalid; a common way to get this wrong is to fail to use NewGlobalRef to convert a local reference to a global reference.

    Generally speaking, JNI became more strict in ICS, so it's peculiar that this would succeed in 4.x but fail in 3.x, unless you're playing around with weak globals.