I was curious about the nature of the handleMessage()
and sendMessage()
behavior of the Handler
class. I want to be able to send message to another thread in such a way that the destination thread can process the message queue when it wants to. It seems, however, that the message is processed by handleMessage()
practically as soon as it's sent.
I'm trying to design a game loop thread that does something like this:
void run(){
while (gameIsActive){
handleInput();
updateGameState();
}
}
handleInput(){
//Remove an item from the handler's message queue
//which can be UI events (click, touch, etc.)
}
However, I as soon as sendMessage() is called (from the parent/calling thread), the Handler.handleMessage() is processed (in the child/receiving thread), even if the child/receiving thread is blocking in a while loop.
I've seen this problem solved in other games by using a thread-safe list (ConcurrentLinkedQueue
). The UI thread just posts events to this queue, and the game loop can remove the events as it seems fit. I just assumed the Handler class was designed for this purpose. It seems it's more intended for asynchronous callbacks to the parent thread.