7
votes

We have this app that loads native library, and this library provides native methods for us to call. On some phones (particularly the slower ones), this causes a problem. An UnsatisfiedLinkError occurs whenever (I think) the library is still being "loaded" and a method is called prematurely.

Is there a way to handle this issue? Like checking if a library is already loaded.

1
Can You post a code how your native library is loaded? I usually use static scope for that. - mar3kk
The library is loaded from a .jar file. Just to point out, though, the libraries are loaded just fine on some phones and doesn't cause the said problem. Here's the bit of code: static { System.loadLibrary("libraryBeingLoaded"); } - hadez30
Are You sure that Your libraries are compiled for architecture You're running on? What if it only contains ARMEABI v7 version and not ARMEABI? Than it won't work on ARMEABI architecture. - mar3kk
Ah, thanks for the link. However, we are using Gradle and it's necessary to place it in a ".jar", according to this link (stackoverflow.com/questions/16683775/…). Also, just to add, when we delay the time that the native method is called (like 3 seconds after the app is loaded), it works fine. 3 seconds is arbitrary, so I didn't go for this hack. The iss - hadez30
Yes, it is, actually. It does work, I'm certain, as there are libraries provided for that architecture. However, the delay is needed, as far as I've tried. - hadez30

1 Answers

4
votes

Even on slower devices, the call to System.loadLibrary() is very fast; but if your app runs multithreaded, or if the class that involves the static constructor is only loaded in response to some UI event - then there could be a race condition: some other classes that rely on the native library being present will cause a crash.

There is no prohibition of using the static constructor which calls System.loadLibrary() for all classes that have native methods. You could see some warnings about native library being loaded multiply, but this does not have negative consequences.

Sometimes, we use custom Java code to extract the native libraries to files directory when the app is run for the first time, instead of relying on the system installer, which puts them into the lib directory. This should be done with extra care, and all activity (pun intended) should wait until extraction of the libs (typically from the assets folder of APK) is complete.

Another catch could be that for some devices, the name of your library may be used by a system library. In such case, System.loadLibrary() will load the library from /system/lib and not from your app; but this can hardly explain the effect of 3 sec delay.