昊仔

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Android中的Timer一般像下面这样写:

java代码:
Timer timer = new Timer( );

TimerTask task = new TimerTask( ) {
public void run ( ) {
Message message = new Message( );
message.what = 1;
handler.sendMessage(message);
}
};

final Handler handler = new Handler( ) {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
log.e("Timer","Timer");
update( );
break;
}

super.handleMessage(msg);
}
};

protected void onDestroy ( ) {
if (timer != null) {
timer.cancel( );
timer = null;
}
super.onDestroy( );
}
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
timer.schedule(task,1000,5000);
}


        最重要的一点是 timer.schedule(task,1000,5000),如果设置为 timer.schedule(task,5000)是不会工作的。

        因为timer.schedule(task,5000) 是表示执行一次的任务。 
        timer.schedule(task,1000,5000)表示 1 秒钟后开始 5 秒钟为周期 重复执行,
        更好的方法是通过下面的代码 (Handler加Runnable线程,更简洁)

java代码:
private Handler handler = new Handler( );

private Runnable runnable = new Runnable( ) {
public void run ( ) {
update( );

handler.postDelayed(this,1000); 
//postDelayed(this,1000)方法安排一个Runnable对象到主线程队列中
}
};

handler.postDelayed(runnable,1000); // 开始Timer
handler.removeCallbacks(runnable); //停止Timer

posted on 2013-10-05 21:08  昊仔  阅读(380)  评论(0编辑  收藏  举报