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

}
};
}

更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. Android移动端自动化测试从入门到实战(Jav
  2. Android—使用ShareSDK实现新浪微博分享
  3. RxJava版本冲突:More than one file was f
  4. android基础入门生命周期(1)
  5. 【Android(安卓)Studio】Camera.Paramete
  6. [置顶] Android(安卓)JavaPoet 动态生成J
  7. Mars之android的Handler(2)
  8. Android(安卓)好的源码依赖包 收集
  9. Cordova开发环境搭建
  10. android 开发技巧(10)--为背景添加圆角边