Skip to content

Instantly share code, notes, and snippets.

@MiguelLavigne
Created April 30, 2015 12:54
Show Gist options
  • Save MiguelLavigne/8809180c5b8fe2fc7403 to your computer and use it in GitHub Desktop.
Save MiguelLavigne/8809180c5b8fe2fc7403 to your computer and use it in GitHub Desktop.
CountUpTimer
/**
* Simple timer class which count up until stopped.
* Inspired by {@link android.os.CountDownTimer}
*/
public abstract class CountUpTimer {
private final long interval;
private long base;
public CountUpTimer(long interval) {
this.interval = interval;
}
public void start() {
base = SystemClock.elapsedRealtime();
handler.sendMessage(handler.obtainMessage(MSG));
}
public void stop() {
handler.removeMessages(MSG);
}
public void reset() {
synchronized (this) {
base = SystemClock.elapsedRealtime();
}
}
abstract public void onTick(long elapsedTime);
private static final int MSG = 1;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
synchronized (CountUpTimer.this) {
long elapsedTime = SystemClock.elapsedRealtime() - base;
onTick(elapsedTime);
sendMessageDelayed(obtainMessage(MSG), interval);
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment