用Timer更新UI

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);
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

}
};
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值