Android实现定时器的三种方法及详解

时间:2022-04-04 00:24:20
  • 新建一个Thread,使用sleep()延时
new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
// Use while to run consistently, use if to run once.
while (true) {
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
doSomething(); //TODO Something
}
}
}.start();
  • 使用Handler的postDelayed()的方法
Handler handler = new Handler();
Runnable runnable=new Runnable() {
@Override
public void run() {
doSomething(); //TODO Something
handler.postDelayed(this, 5 * 1000); //Put the statment here to run consistently, remove it to run once
}
};

handler.postDelayed(runnable, 5 * 1000); //Start Timer
Handler的postDelayed(Runnable r, long delayMillis)方法与postAtTime(Runnable r, long uptimeMillis)方法的区别:
postDelayed是在延迟x秒后执行执行操作, postAtTime是在特定的时间XX:YY:ZZ.mmm进行执行操作。
注意事项: 一般会使用如下代码进行handler的取消:
handler.removeCallbacks(runnable); //Stop Timer
但是当某些特定的时候,removeCallbacks()可能会失效。例如当Activity转入后台再转入前台之后,再调用removeCallbacks()方法,会发现runnable无法正确地从队列中被移除。原因是当Activity转入后台后,runnable仍旧在运行,但当Activity重新转入前台后,会重新定义Runnable runnable。因此之前在运行的runnable无法被正确移除。
解决方法是将handler和runnable定义成静态的,JVM只会为静态变量分配一次内存。
static Handler handler = new Handler();  
static Runnable runnable = new Runnable() {

@Override
public void run() {
@Override
public void run() {
doSomething(); //TODO Something
handler.postDelayed(this, 5 * 1000); //Put the statment here to run consistently, remove it to run once
}
}
};
  • 设置Timer及TimerTask
private final Timer timer = new Timer(); 
private TimerTask task;

task = new TimerTask() {
@Override
public void run() {
doSomething(); //TODO Something
}
};

timer.schedule(task, 5 * 1000, 5 * 1000);