Skip to content

Instantly share code, notes, and snippets.

@leandrofavarin
Created January 13, 2015 00:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leandrofavarin/384437026833b35969fb to your computer and use it in GitHub Desktop.
Save leandrofavarin/384437026833b35969fb to your computer and use it in GitHub Desktop.
An Android CountDownTimer that can be paused and resumed
package com.leandrofavarin.tools;
import android.os.CountDownTimer;
public class PausableCountDownTimer {
long millisInFuture = 0;
long countDownInterval = 0;
long millisRemaining = 0;
public CountDownTimer countDownTimer = null;
boolean isPaused = true;
public PausableCountDownTimer(long millisInFuture, long countDownInterval) {
super();
this.millisInFuture = millisInFuture;
this.countDownInterval = countDownInterval;
this.millisRemaining = this.millisInFuture;
}
private void createCountDownTimer() {
countDownTimer = new CountDownTimer(millisRemaining, countDownInterval) {
@Override
public void onTick(long millisUntilFinished) {
millisRemaining = millisUntilFinished;
CountDownTimerPausable.this.onTick(millisUntilFinished);
}
@Override
public void onFinish() {
CountDownTimerPausable.this.onFinish();
}
};
}
/**
* Callback fired on regular interval.
*
* @param millisUntilFinished
* The amount of time until finished.
*/
public abstract void onTick(long millisUntilFinished);
/**
* Callback fired when the time is up.
*/
public abstract void onFinish();
/**
* Cancel the countdown.
*/
public final void cancel() {
if (countDownTimer != null) {
countDownTimer.cancel();
}
this.millisRemaining = 0;
}
/**
* Start or Resume the countdown.
*
* @return CountDownTimerPausable current instance
*/
public synchronized final CountDownTimerPausable start() {
if (isPaused) {
createCountDownTimer();
countDownTimer.start();
isPaused = false;
}
return this;
}
/**
* Pauses the CountDownTimerPausable, so it could be resumed(start) later
* from the same point where it was paused.
*/
public void pause() throws IllegalStateException {
if (isPaused == false) {
countDownTimer.cancel();
}
isPaused = true;
}
public boolean isPaused() {
return isPaused;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment