How to pause, and resume a TimerTask/ Timer

After a TimerTask is canceled, it cannot run again, you have to create a new instance.

Read details here:

https://stackoverflow.com/a/2098678/727768

ScheduledThreadPoolExecutor is recommended for newer code, it handles the cases like exceptions and task taking longer time than the scheduled interval.

But for your task, TimerTask should be enough.


Here's how I did it. Add pauseTimer boolean where ever the pause takes place (button listener perhaps) and don't count timer if true.

private void timer (){
    Timer timer = new Timer();
    tv_timer = (TextView) findViewById(R.id.tv_locationTimer);
    countTimer = 0;
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String s_time = String.format("%02d:%02d:%02d",
                            countTimer / 3600,
                            (countTimer % 3600) / 60,
                            countTimer % 60);
                    tv_timer.setText(s_time);
                    if (!pauseTimer) countTimer++;
                }
            });
        }
    }, 1000, 1000);
}