Created
January 13, 2015 00:14
-
-
Save leandrofavarin/384437026833b35969fb to your computer and use it in GitHub Desktop.
An Android CountDownTimer that can be paused and resumed
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
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