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()
orcancel()
on theTimer
instead of theTimerTask
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); } }};
using your code, instead of
scanTask.cancel();
the correct way is to cancel your timer (not timerTask):
t.cancel();
The Android documentation says that cancel() Cancels the Timer and all scheduled tasks. If there is a currently running task it is not affected. No more tasks may be scheduled on this Timer. Subsequent calls do nothing. Which explains the issue.