JNI problems in unity

Hi everyone.

I have encountered some JNI problem which happens on some Android device using ICS (Android 4.0.4). Below is the CatLog

08-29 09:33:56.457: E/Unity(18890): Initializng Facebook!!!
08-29 09:33:56.457: E/Unity(18890):
08-29 09:33:56.457: E/Unity(18890): (Filename: ./Runtime/ExportGenerated/AndroidManaged/UnityEngineDebug.cpp Line: 43)
08-29 09:33:56.457: I/Unity(18890): CallStatic(“instance”) = ()Ljava/lang/Object;
08-29 09:33:56.457: I/Unity(18890):
08-29 09:33:56.457: I/Unity(18890): (Filename: ./Runtime/ExportGenerated/AndroidManaged/UnityEngineDebug.cpp Line: 43)
08-29 09:33:56.457: I/Unity(18890): method id not cached; doing lookup (static)
08-29 09:33:56.457: I/Unity(18890):
08-29 09:33:56.457: I/Unity(18890): (Filename: ./Runtime/ExportGenerated/AndroidManaged/UnityEngineDebug.cpp Line: 43)
08-29 09:33:56.465: E/dalvikvm(18890): JNI ERROR (app bug): accessed stale weak global reference 0x13 (index 4 in a table of size 0)

May I ask if any one has encountered similar situation and know what is going on?
Thank you

It is likely that the Java object you are trying to access has gone out of scope, or has a return value other than void.

So, when you make the call to CallStatic, you should probably quality the return value as an AndroidJavaObject.

Take a look at the C# script below:

using (AndroidJavaClass unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer") )
{
   using (AndroidJavaObject activity = unityClass.GetStatic<AndroidJavaObject>("currentActivity") )
   {	
      activity.Call("startSensorService");			
   }
}

You’ve probably seen this type of code in plugin examples. In the 2nd using statement, it calls a static member function of UnityPlayer to get the current activity object. If I called unityClass.GetStatic(“currentActivity”) without the qualifier, I’d get an error saying “can’t find method id”.

Also, if for some reason the return value from the Java code were null, a different kind of error would happen, which is also pretty common, the “JNI: Init’d AndroidJavaObject with null ptr” error.

The best to to avoid that error is to go into the Java code and make sure that these functions return something, or if they can’t create another method like “hasInstance” or some such that can make sure the value you are about to return is a valid one.