Search code examples
javaandroidmultithreadingandroid-ndkjava-native-interface

Loading JNI libs- via Java threads or NDK pthreads?


I am loading many .so libraries into Android application. When I make JNI call, function in library.so runs an infinte loop, so it never returns to calling function. Should I make JNI call from Java thread or should I load a function from pthreads in a library? Which is better?

Second question: how can I be sure that libraries are unloaded when user exits MainActivity? Thanks.


Solution

  • For the first question, basically what Alex said. It should not make much of a difference if you choose Java or pthreads.

    For the second question, you should stash a pointer to the created libraries in your Java code. The easiest way is for your Jni call to return this pointer as a jlong. But since, your jni function never returns, you will have to directly set the value in the native code.

    Checkout the implementation of the NativeHandle class here

    http://thebreakfastpost.com/2012/01/26/wrapping-a-c-library-with-jni-part-2/

    Then before the main activity exits (I presume in the onDestroy() method) make a call to a jni function to stop libraries from running