Search code examples
androidmultithreadingandroid-ndkjava-native-interface

Android NDK: JNI "main" to deal with messages?


I'm trying to build an Android application that uses an existing C library for some background operation (i.e. does some radio scans, tunes to stations etc). As a stand-alone C executable, the main-loop can deal with message handling from lower levels (hardware components). My understanding is that using JNI, no main function is required because

1) a shared library is created and

2) the shared library is "alive" for as long as the java thread that loaded it is alive.

So assuming that the C library uses multiple threads: where should then the message handling that normally is done in the initial main-loop be done? Is it as simple as by calling C functions that are declared together with the JNI functions?


Solution

  • Re 2) library is "alive" in the meaning of persisting in the memory. But it does not do anything on its own. If you need the library to "do something" even if no functions are being called through JNI, then you need a separate native thread of course. You can create the thread and start a message loop within a regular JNI function call (init method or use JNI_OnLoad for that purpose). It will keep on running when the JNI function call returns. You then also need a teardown method which stops the thread and tears it down (JNI_OnUnload can be used for that)