Android Timer and UI threads
In the past few days I was trying to create a daemonized timer without too much luck, then after sweating blood I managed to come up with the following code:
public class SampleTimer extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.yourlayout);
// we create a new timer
// arg0 -- String - The timer's name
// arg1 -- Boolean- Whether the timer should be daemonized
Timer timer = new Timer("MyTimerName", true);
timer.schedule(new TimerTask() {
@Override
public void run() {
// method to repeat
SampleMethod();
}
// initial delay is 0 seconds
// and SampleMethod() will run every
// 1.8 million milliseconds (30mins)
}, 0, 1800000);
}
private void SampleMethod(){
// we run a new worker thread on the UI thread
this.runOnUiThread(worker);
}
private Runnable worker = new Runnable() {
public void run() {
// do some checks then send notification (upcoming post)
}
};
}
This piece of code, without the class container, is actually used in another background thread (in a class which extends Activity and implement Runnable). I bet if a long-time Java programmer would see my code, would cut my throat, but hey, it works :)
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home