I’m building an Android native application where most of the business logic resides in C++.
For example, UI events like Key Press or Drag-Drop arrive on the main thread. To process them, I forward these events into C++ through JNI. Sometimes, determining the action to take can be time-consuming, so I don’t want to block the main thread. The OS generally expects such work to be done on a background thread.
The challenge is:
If I move event handling to background threads, how do I ensure that events are still executed sequentially in the same order they were received?
What is the recommended approach to forward events to C++ while keeping UI responsive and event order preserved?
Here’s a simplified version of what I have now:
// Kotlin side (UI thread)
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
// Forward event to C++ via JNI
return NativeBridge.onKeyEvent(keyCode, event.action)
}
// C++ side
bool onKeyEvent(int keyCode, int action) {
// This may take time...
processEvent(keyCode, action); // So, I want to make this call go async...
return ? // Here, is where I am confused
}
How should I structure this event dispatching (Java → JNI → C++ → background thread) so that:
- The UI thread isn’t blocked.
- Events are always processed in the same order they were received.
Some events (e.g., KeyPress on a TextField) have synchronous implications:
If I return false, the OS also updates the text.
If I return true, the OS does nothing, and I’d need to manually update the text.
If I process these events asynchronously, I can’t immediately decide whether to return true or false.
This seems to force me into manual string management, which I’d like to avoid if possible. Is there a recommended way to handle such cases?