February 24, 2021
Hot Topics:

Handling Lengthy Operations in Google's Android, Page 3

  • By Chunyen Liu
  • Send Email »
  • More Articles »

Using Message Handlers to Post Back Results

First, each message should be associated with an ID that can be randomly assigned by you, but you need to guarantee its uniqueness among all the messages. In the example, you use GUIUPDATEIDENTIFIER as your message ID. Because the child threads cannot modify the view in the main thread directly, we need to update the main view myview with myview.invalidate() when the message handler receives the message ID from a child thread.

The example result is illustrated in Figure 3.

// Set up a random unique ID for message handler
protected static final int GUIUPDATEIDENTIFIER = 12345;

// Set up the message handler
Handler myGUIUpdateHandler = new Handler() {

   // @Override
   public void handleMessage(Message msg) {
      switch (msg.what) {
         case TutorialOnANR.GUIUPDATEIDENTIFIER:


Figure 3: Final updated result

A Working Example

In addition to what I described earlier about the creations of Thread, Message, and Handler, you construct the content view from MyView by dynamically instantiating it in Activity's OnCreate instead of configuring the resources through an XML file.

You also set a key event handler to wait for the user's input by hitting the middle button of the direction pad. That completes the example.

// Set up the main view and random points
MyView myview = null;
MyPoint[] mypoint = null;

protected void onCreate(Bundle icicle) {

   myview = new MyView(this);


public boolean onKeyDown(int keyCode, KeyEvent event) {
   if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {

      // Uncomment the following 2 lines to test the case of
      // no child thread and no message handling
      // setRandomPoints(false);
      // myview.invalidate();

      // Set points with a child thread and message handling

      return (true);

   return super.onKeyDown(keyCode, event);

// Define the class for main view
public class MyView extends View {
   private Paint mPaint = new Paint();

   public MyView(Context context) {

      mPaint.setARGB(255, 255, 255, 255);

   @Override protected void onDraw(Canvas canvas) {

      if (mypoint != null) {
         for (int i = 0; i < mypoint.length; i++) {
            canvas.drawCircle(mypoint[i].x, mypoint[i].y,
               mypoint[i].sz, mPaint);


// Define the class for our random point
class MyPoint {
   float x;
   float y;
   int   c;
   float sz;

Page 3 of 4

This article was originally published on July 30, 2008

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date