一、三种常用的定时器 :
1.handler+timer的方法:
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1){
//要执行的任务
}
super.handleMessage(msg);
}
};
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
// 主线程中调用:timer.schedule(timerTask,延时时长,执行一次任务所需时间);
2、handler+线程的方法:
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1){
//要执行的任务
}
super.handleMessage(msg);
}
};
class MyThread extends Thread {//这里也可用Runnable接口实现
@Override
public void run() {
while (true){
try {
Thread.sleep(延时时长);
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 主线程中调用方法:new Thread(new MyThread()).start();
3、Handler的postDelayed方法:
Handler handler = new Handler();
Runnable r = new Runnable() {
@Override
public void run() {
//要执行的任务
handler.postDelayed(this, 执行一次所需的时长);
}
};
// 主线程中调用: handler.postDelayed(r, 延时时长);
网友评论