Android – Controlling a task with Timer and TimerTask?

You might consider:

  • Examining the boolean result from calling cancel() on your task, as it should indicate if your request succeeds or fails
  • Try purge() or cancel() on the Timer instead of the TimerTask

If you do not necessarily need Timer and TimerTask, you can always use postDelayed() (available on Handler and on any View). This will schedule a Runnable to be executed on the UI thread after a delay. To have it recur, simply have it schedule itself again after doing your periodic bit of work. You can then monitor a boolean flag to indicate when this process should end. For example:

private Runnable onEverySecond=new Runnable() {
    public void run() {
        // do real work here

        if (!isPaused) {
            someLikelyWidget.postDelayed(onEverySecond, 1000);
        }
    }
};

Leave a Comment