3

I have been getting sporadic, difficult to reproduce UnsatisfiedLinkErrors, most commonly when my application has been paused for a long time (i.e., hours). These errors occur on JNI calls that normally work.

Does Android sometimes unload a library without completely closing an application? I load my native library in one activity but also use it in another activity. Could Android be destroying the activity that loaded the library and unloading it, then failing to reload the library when the other activity that uses it is resumed?

pbsurf
  • 31
  • 1
  • Can you determine (say by checking the process ID) if the "resume" of the activity is occurring in the same process in which the library was originally loaded? My suspicion is that the resume is occurring in a new process in which it was never loaded. – Chris Stratton May 18 '12 at 04:22
  • Assuming that this is the case, what would be the proper way to ensure that the library is loaded exactly once regardless of which activity starts first in the new process? – pbsurf May 18 '12 at 17:35
  • How about simply trying to load it in every activity where it is needed? http://java.sun.com/docs/books/jni/html/design.html suggests "System.loadLibrary completes silently if an earlier call to System.loadLibrary has already loaded the same native library." – Chris Stratton May 18 '12 at 17:41
  • Thanks @Chris. I was loading the library in my top level Activity but had declared all its methods in a different Activity. Loading the library in a static block in the same activity where the methods are declared seems to fix the problem. The static block appears to be executed on the first invocation of any of the static native methods, even if no instance of the Activity has been created yet. – pbsurf May 21 '12 at 00:38

1 Answers1

1

Everytime you load a library with an Activity like this,

   static {
        System.loadLibrary("gamescript");
    }       

Then the library is loaded within the Activity class like a local static member and will not be unloaded until the app is alive. However, my doubt is if it will be accessible from outside the class.

codetiger
  • 2,650
  • 20
  • 37
  • Do you have any evidence which suggests that the unloading would actually happen? – Chris Stratton May 18 '12 at 17:42
  • @ChrisStratton Sorry, the earlier statement was wrong. Thanks for pointing out. – codetiger May 19 '12 at 04:12
  • Like this answer below says, static members are stored in Permanent Generation section http://stackoverflow.com/a/3800592/409315 – codetiger May 19 '12 at 04:26
  • Well, actually, the library itself gets loaded into the DVM process by the bionic runtime linker (think C concepts rather than java concepts). But I suppose it's possible there is some java-level data regarding its existence to enable jni that could be handled the way you suggest. – Chris Stratton May 19 '12 at 05:29