我们平时常常会用到timer,不过将timer放在主线程会加重主线程的负担
所以我们更偏向于使用多线程实现timer,每隔1段时间再通知主线程更新ui
大致思路:
- 使用thread,run,handler,msg实现多线程
- 使用timer,timerTask实现定时器功能
我们先来实现主线程中,更新ui的功能
新建1个handler,收到指定任务的code时,就履行我们定义的步骤
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if (msg.what == task_code) {
//timer action
}
}
};
我们现在另外开1个线程类,我们可以想到,他需要几个参数,handler+delay的长度(毫秒)+时间间隔(毫秒)+任务code,为了安全起见,我把context也加上了
public TimerThread(Context context, Handler handler, int delay,
int interval, int task_code) {
// TODO Auto-generated constructor stub
this.handler = handler;
mContext = context;
this.delay = delay;
this.interval = interval;
this.task_code = task_code;
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
Message msg = new Message();
msg.what = task_code;
handler.sendMessage(msg);
}
}, delay, interval);// schedule(timerTask,delay duration,timer task duration)
}
是长这个模样的
要调用timertask的时候,就
TimerThread timerThread = new TimerThread(this, handler,1000,1000,task_code);
timerThread.start();
想停止timer,就
timerThread.timer.cancel();
好了
代码在这里:→http://download.csdn.net/detail/edwardwayne/8647501