Reputation: 15
I know there are a lot of threads with the same topic, but I do not want to use some random code I do not understand.
This is my current code to pause and continue a CountDownTimer in Android Studio:
public void getReadyTimer(long time){
time = 12000;
progress=0;
circularProgressBar.setProgress(0);
//tvInfo.setText("Get Ready!");
timer= new CountDownTimer(time, 1000) {
public void onTick(long millisUntilFinished) {
milliLeft = millisUntilFinished;
sec = ((millisUntilFinished-1000)/1000);
tvTimer.setText(Long.toString(sec));
//tvTimer.setText((millisUntilFinished-1000) / 1000 + "");
progress++;
int animationDuration = 1500; // 2500ms = 2,5s
circularProgressBar.setProgressWithAnimation((int)progress*100/(11000/1000), animationDuration);
circularProgressBar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (t== 0) {
pauseTimer();
t =1 ;
tvInfo.setText(Integer.toString(t));
}else{
resumeTimer();
t = 0;
tvInfo.setText(Integer.toString(t));
}
}
});
}
private void pauseTimer(){
timer.cancel();
}
private void resumeTimer(){
Log.i("sec", Long.toString(sec));
milliLeft = sec*1000;
getReadyTimer(milliLeft);
}
public void onFinish() {
if (circularProgressBar.getProgress() == 100) {
startTimer();
}
}
}.start();
}
However it does not work properly. The problem is, that the Timer (after pausing) starts again with the value "time" and not with "millileft" as it should be. I appreciate every kind of help.
Upvotes: 0
Views: 6385
Reputation: 2847
Use this, may help you
Global Variables
private CountDownTimer timer;
long time = 12000;
Timer
private void startTimer(long timerStartFrom) {
timer = new CountDownTimer(timerStartFrom, 1000) {
@Override
public void onTick(long millisUntilFinished) {
//updating the global variable
time = millisUntilFinished;
}
@Override
public void onFinish() {
}
}.start();
}
In Initial(onCreate)
How to Start
start your timer with
startTimer(time)
as time has initial value //12000
How to Pause
then you can pause/cancel timer
by using timer.cancel()
How to Resume
and when you want to resume just start your timer by calling startTimer(time)
as the timer has the updated value.
What will it does it will start your timer with previous time where you have stops your timer
Simple, Happy coding :)
Upvotes: 1
Reputation: 37614
You are re-assigning the value of the passed parameter milliLeft
to 12000
. To fix this you can create two methods. One which accepts a parameter and the other without. e.g.
public void getReadyTimer() {
this.getReaderTimer(12000L); // default value
}
public void getReadyTimer(long time) {}
In the parameterized method remove the assignation of
time = 12000;
Upvotes: 0
Reputation: 1451
You shouldn´t call timer.cancel()
to pause the timer. And afterwards you can call timer.resume() to start it again. There is no need to use so "complicated" logic.
Have a look here: Android: timer start, pause, stop
Upvotes: 0