android 开发中定时器的三种实现方式:
1: 采用Handler与线程的sleep(time)方法
2:采用Handler的postDelayed(Runnable, long)方法
3:采用Handler与timer及TimerTask结合的方法
1:采用Handler 与线程Sleep(time)方法
1. 定义一个Handler类,用于处理接受到的Message。
Handler handler = new handler(){
public
void
handleMessage(Message msg) {
//do
something
super
.handleMessage(msg);
}
2. 新建一个实现Runnable接口的线程类,如下:
public
class
MyThread
implements
Runnable {
@Override
public
void
run() {
// TODO Auto-generated method stub
while
(
true
) {
try
{
Thread.sleep(
10000
);
//
Message message =
new
Message();
message.what =
1
;
handler.sendMessage(message);
//
}
catch
(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
3:启动线程
newThread(
new
MyThread()).start();
二、采用Handler的postDelayed(Runnable, long)方法
1. 定义一个Handler类
Handler
handler=
new
Handler();
Runnable
runnable=
new
Runnable() {
@Override
public
void
run() {
// TODO Auto-generated method stub
//do something
handler.postDelayed(
this
,
2000
);
}
};
2. 启动计时器
handler.postDelayed(runnable,
2000
);//2000ms
3:停止计数器:
handler.removeCallbacks(runnable);
三、采用Handler与timer及TimerTask结合的方法
1:定义定时器,定时器任务,和handler句柄:
private
final
Timer timer =
new
Timer();
private
TimerTask task;
Handler
handler =
new
Handler() {
@Override
public
void
handleMessage(Message msg) {
// TODO Auto-generated method stub
// 要做的事情
super
.handleMessage(msg);
}
};
2:初始化任务:
task
=
new
TimerTask() {
@Override
public
void
run() {
// TODO Auto-generated method stub
Message message =
new
Message();
message.what =
1
;
handler.sendMessage(message);
}
};
3:开始任务
timer.schedule(task,
2000
,
2000
);