timer+thread 入門,簡(jiǎn)單封裝
來(lái)源:程序員人生 發(fā)布時(shí)間:2015-05-12 09:23:34 閱讀次數(shù):3510次
我們平時(shí)常常會(huì)用到timer,不過將timer放在主線程會(huì)加重主線程的負(fù)擔(dān)
所以我們更偏向于使用多線程實(shí)現(xiàn)timer,每隔1段時(shí)間再通知主線程更新ui
大致思路:
- 使用thread,run,handler,msg實(shí)現(xiàn)多線程
- 使用timer,timerTask實(shí)現(xiàn)定時(shí)器功能
我們先來(lái)實(shí)現(xiàn)主線程中,更新ui的功能
新建1個(gè)handler,收到指定任務(wù)的code時(shí),就履行我們定義的步驟
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if (msg.what == task_code) {
//timer action
}
}
};
我們現(xiàn)在另外開1個(gè)線程類,我們可以想到,他需要幾個(gè)參數(shù),handler+delay的長(zhǎng)度(毫秒)+時(shí)間間隔(毫秒)+任務(wù)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)
}
是長(zhǎng)這個(gè)模樣的
要調(diào)用timertask的時(shí)候,就
TimerThread timerThread = new TimerThread(this, handler,1000,1000,task_code);
timerThread.start();
想停止timer,就
timerThread.timer.cancel();
好了
代碼在這里:→http://download.csdn.net/detail/edwardwayne/8647501
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)