标签:thread 多线程 timer android android开发
我们平时经常会用到timer,不过将timer放在主线程会加重主线程的负担
所以我们更倾向于使用多线程实现timer,每隔一段时间再通知主线程更新ui
大致思路:
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if (msg.what == task_code) {
//timer action
}
}
};我们现在另外开一个线程类,我们可以想到,他需要几个参数,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)
}是长这个样子的TimerThread timerThread = new TimerThread(this, handler,1000,1000,task_code); timerThread.start();想停止timer,就
timerThread.timer.cancel();好了
标签:thread 多线程 timer android android开发
原文地址:http://blog.csdn.net/edwardwayne/article/details/45378783