-
-
Save MiguelLavigne/8809180c5b8fe2fc7403 to your computer and use it in GitHub Desktop.
CountUpTimer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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