Android SDK, Timers and GUI Update

February 10th, 2009 | by Ozgur Cem Sen |

Here is some piece-meal code for folks looking for information about how to implement a sort-of-a-timer and GUI update in Android based applications.

Some initial definitions;

1
2
3
private Handler handlerTimer = new Handler();

private static final int UPDATE_STUFF_ON_DIALOG = 999; //this is a true arbitrary number.

Init the timer at some point. Perhaps on “onCreate”, or where ever you need it.

1
2
handlerTimer.removeCallbacks(taskUpdateStuffOnDialog );
handlerTimer.postDelayed(taskUpdateStuffOnDialog , 100); //set a 100 milisecond delay for the initial post

The Runnable thread that will possibly do some lengthy operation;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private Runnable taskUpdateStuffOnDialog = new Runnable() {
       public void run() {     

            /*
               Do some lengthy stuff here !!!
            */

   
            // handling be in the dialog
            // don't mess with GUI from within a thread
            Message msg = new Message();
            msg.what = UPDATE_STUFF_ON_DIALOG;
            handlerEvent.sendMessage(msg); 

            //Do this again in 30 seconds          
            handlerTimer.postDelayed(this, 30000);
    }
};

taskUpdateStuffOnDialog task will post the message to the main dialog’s event handler, where we will finally do some GUI stuff.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private Handler handlerEvent = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case UPDATE_STUFF_ON_DIALOG: {

             // have a go at your GUI stuff here. enable/disable stuff, flash things, change text...

        }
            break;         
        default: {
            super.handleMessage(msg);
        }
            break;         
        }
    }
};

That’s it.

  1. 2 Responses to “Android SDK, Timers and GUI Update”

  2. By chris on Mar 11, 2009 | Reply

    hi nice.
    i am a total android newbie

    can you send me a complete example.
    when i put your pieces together i get several errors in my sdk 1.1

    thanks
    chris

  3. By Cem on Mar 11, 2009 | Reply

    hi there,

    what are the errors you’re getting? you might be missing some imports, perhaps?

Sorry, comments for this entry are closed at this time.