views:

23

answers:

1

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.

A: 

Well, I can't find a good answer about this timing (and it would be useful to know in other instances), but, as a workaround I just used a public List that was thread safe, and my UI thread can access this public list and add information to it. In particular I used a ConcurrentLinkedQueue. I found this in the official JetBoy game sample provided by Google, so maybe they don't even encourage using the Handler in this situation :)

John Tabs