使用 Handler 创建一个 Timer(类似于 javax.swing.Timer)
如果你正在编写游戏或需要每隔几秒钟执行一段代码的内容,这将非常有用。
import android.os.Handler;
public class Timer {
private Handler handler;
private boolean paused;
private int interval;
private Runnable task = new Runnable () {
@Override
public void run() {
if (!paused) {
runnable.run ();
Timer.this.handler.postDelayed (this, interval);
}
}
};
private Runnable runnable;
public int getInterval() {
return interval;
}
public void setInterval(int interval) {
this.interval = interval;
}
public void startTimer () {
paused = false;
handler.postDelayed (task, interval);
}
public void stopTimer () {
paused = true;
}
public Timer (Runnable runnable, int interval, boolean started) {
handler = new Handler ();
this.runnable = runnable;
this.interval = interval;
if (started)
startTimer ();
}
}
用法示例:
Timer timer = new Timer(new Runnable() {
public void run() {
System.out.println("Hello");
}
}, 1000, true)
此代码将每秒打印 Hello
。