Android SDK, Timers and GUI Update
Tuesday, February 10th, 2009Here 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.
![i.am.codingthings.[com]. software things. Ozgur Cem Sen](http://me.codingthings.com/wp-content/themes/big-blue-01/images/logo.gif)
