使用 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
。