Você está na página 1de 2

Timers in Android | Steve Ody

http://steve.odyfamily.com/?p=12

Steve Ody
Programmer, Gamer, Amiga & C64 fan!

Timers in Android
Posted on February 23, 2009 by steve Finding clear information on the web about setting up a Timer in Android seems to be a rough task. The general consensus is that the android.os.Handler class should be used instead via the postDelayed() method. In general, this process seems like a valid way to achieve the timer. However, when you want a timer to actually function like a timer, for example, running some process every second, on the second, you quickly see the problems caused by using the postDelayed() method. More information on using the postDelayed() method can be found here: http://android-developers.blogspot.com/2007/11/stitch-in-time.html Using the process described above, if you have a method that you want to call every second (Timer_Tick), and the method itself takes between 100ms 200ms to complete, after which you do a postDelayed() to run it again in 1000ms, you end up with a timer that runs every 1.2 seconds, and grows progressively out of sync with real time. I suppose you could correct this by determining how long the method took to run, then calling postDelayed with the adjusted time, but that would not be as reliable as an actual timer. Using an actual Timer (java.util.Timer) in conjunction with runOnUiThread() is one way to solve this issue, and below is an example of how to implement it.

public class myActivity extends Activity { private Timer myTimer; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle);

1 de 2

03/03/2012 09:21

Timers in Android | Steve Ody

http://steve.odyfamily.com/?p=12

setContentView(R.layout.main); myTimer = new Timer(); myTimer.schedule(new TimerTask() { @Override public void run() { TimerMethod(); } }, 0, 1000); } private void TimerMethod() { //This method is called directly by the timer //and runs in the same thread as the timer. //We call the method that will work with the UI //through the runOnUiThread method. this.runOnUiThread(Timer_Tick); } private Runnable Timer_Tick = new Runnable() { public void run() { //This method runs in the same thread as the UI. //Do something to the UI thread here } }; }

Hopefully this is clear, and can help others that need to address this situation. This entry was posted in Uncategorized by steve. Bookmark the permalink [http://steve.odyfamily.com/?p=12] .

Comments are closed.

2 de 2

03/03/2012 09:21

Você também pode gostar