Search code examples
c++candroid-ndkjava-native-interfaceposix-select

Porting a select loop application to Android with NDK. Design question


I have an network application which uses a select loop like this:

bool shutdown=false;
while (!shutdown) {

     [do something]
     select(...,timeout);
}

THe main loop cannot work like this in an Android application anymore since the application needs to receive Intents, need to handle GUI, etc.

I think I have basically three possibilities:

  1. Move the main loop to the java part of the application.
  2. Let the loop run in its own thread and somehow communicate from/to java.
  3. Screw Android <= 2.3 and use a native activity and use AInputQueue/ALooper instead of select.

The first possibility is not easy since java has no select which works on fds. Simply using the select and return after each loop to java is not an elegant possibility either since that requires setting the timeout to something like 20ms to have a good response time in the java part of the program.

The second probability sound nicer but I have do some communication between java and the c++/c part of the program. Things that cold work:

  1. Using a socket, kind of ugly.
  2. using native calls in the "java gui thread" and callback from native in the "c thread". Both threads need to have thread safe implementations but this is managable.

I have not explored the third possibility but I think that it is not the way to go.

I think I can hack something together which will work but I asking what is the best path to chose.


Solution

  • Based on limited info provided, I can think of following approach:

    A loop can run in a separate thread with two options:
    a) look for gui led changes (based on value of a global native state variable say, native_app_state, of enum type)
    b) something happens that triggers a callback to Java

    You can have separate native functions or one integrated native function to respond to GUI events from Java - where you can use the state of that global native state variable.

    You can optimize the implementation based on what happens in each state, and the performance constraints of the application.