Home Tutorials Hands on The Android Message Queue
The Android Message Queue
Monday, 03 November 2008 00:00
Article Index
The Android Message Queue
Lets get quacking
All Pages

Ducks in a rowAt their heart, computers are pretty simple beasts: they only do what you tell them to. Sometimes though, it looks like they are responding to events being fired from all directions at once. Well, thats because they've been told how to deal with those "random" events by interrupting the current flow. In Android a mechanism for this is called the Message Handling System. It's a way of writing software that can be interrupted at any time by predefined messages. These messages are generated by real world events like timers firing or the keyboard being opened, so here's an Android application to illustrate it.

 

Tutorial: Message Queue Skill: Medium Market install Download source

Keeping with the idea of queueing, our application first draws a duck pond with a bunch of randomly placed baby ducks present, then waits for a finger press. When that arrives, momma duck is drawn and all the baby ducks then move to line up behind her. The twist is every baby duck movement is in response to a timed message which is sent only when they need moving.

Heres how it looks when run:

 

     

 

The basics are very similar to the wash your hands application but this time we're performing more calculations and setting up the message handling system. The new object which does all the work is the Handler, and we create an instance in our View class called "handler". You can think of this as the listener for any messages aimed at our class, and in this case the messages are sent using the sendMessageDelayed() method. At any point, we can create our custom message, call sendMessageDelayed() to fire it at our class and the handler will receive, analyse, and act on it if its appropriate to do so. Notice the send method used is called sendMessageDelayed() - thats because it takes an extra argument which allows for a delay before the message is added to the queue. The message queue is an internal structure which the handler constantly loops over, pulling each message out in turn. We make use of the delay value to make sure our baby ducks don't swim too fast or too slow.

Its important to realise the messages are processed asyncronously, that is they don't wait for the current task to finish. You can see this if you keep moving momma duck: the babies don't stop until you stop moving her, they keep on moving towards her no matter where she is on the screen. The task of moving momma is interrupted by the messages fired telling the babies to update their positions.



 

Add comment


Security code
Refresh

Copyright © 2012 Android Academy. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.
 
Glossary
We have 48 guests online