Ranjit Pati Ranjit Pati - 5 months ago 112
Android Question

Android: Pause/Resume Timer OR Thread

I have checked all SO answers about how to pause/resume timer, but can't find a solution.

I have created a Timer task which counts the effort time for an employee and puts it inside a TextView to show.

Code below:

Timer T = new Timer();
T.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
String workingTime = "Your effort is "
+ format.format(Double.valueOf(hr)) + ":"
+ format.format(Double.valueOf(min)) + ":"
+ format.format(Double.valueOf(sec))
+ " till now for the day";
storeEffort.setText(workingTime);
sec++;
if (sec > 59) {
sec = 0;
min = min + 1;
}
if (min > 59) {
min = 0;
hr = hr + 1;
}
}
});
}
}, 1000, 1000);


where storeEffort is my TextView which shows the effort time which is stuck inside the running thread(main problem). I want to pause the effort timer with a button click and resume it when the same button clicked again.Is there any other way to do this kind of task?

Answer

You solution might have a slight problem - you are using timer to count time intervals whereas there is no need to. You could use i.e. StopWatch to count elapsed time. So instead of adding seconds in a timer job you could just get elapsed time from this timer. To pause the timer you could call stopWatch.stop() and to start it, you could call stopWatch.start().

It could look like this:

Stopwatch stopwatch = Stopwatch.createStarted();

void startThreadUpdateTimer(){}
    Timer T = new Timer();
    T.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String workingTime = "Your effort is " + sw.toString() + 
                         " till now for the day";                        
                }
            });
        }
    }, 1000, 1000);
}

public void pause(){
    if(stopwatch.isRunning()){
        stopwatch.stop();
    }
}

public void resume(){
    if(!stopwatch.isRunning()){
        stopwatch.start();
    }
}