Is it possible to pause a CountDownTimer in Android? I have been looking for good solutions but I just find some ways to do this that I really don't like. As just save the left time in a variable and initialize a new CountDownTimer with that values.
That kind of solutions work but they didn't look so good because I′m using a circle Progress bar and a Textview together with my countdownTimer. Was really ugly try to look this two look good with the CountDown without be able to really "pause" it.
Here is my code for initialize the CountDownTimer with a ProgressBar and a TextView.
public void initProgress() {
if (mCountdownProgressBar == null)
mCountdownProgressBar = (CircleProgressBar) findViewById(R.id.progressBar);
mCountDownTime = 30000; //Insert your desire time in Milliseconds here
mCountdownProgressBar.setMaxProgress((int)TimeUnit.MILLISECONDS.toSeconds(mCountDownTime));
mCountDownTimer = new CustomCountDownTimer(mCountDownTime, 1000) {
@Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress" + TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished));
mCountdownProgressBar.setmProgress(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished));
mTimer.setText(Util.getTimeForTimer(millisUntilFinished, Util.TIME_FORMAT));
}
@Override
public void onFinish() {
mCountdownProgressBar.setmProgress(0);
mTimer.setText(Util.getTimeForTimer(0, Util.TIME_FORMAT));
}
};
mCountDownTimer.start();
}
With this code you will be able to set a progressBar and a TextView together with your CountDownTimer. To be able to pause and resume it pretty easy I will post next a Custom Class for CountDownTimer.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…