Filipe Gonçalves Filipe Gonçalves - 3 months ago 38
Android Question

Stop a task from the timer task

I have a

Timer
and I schedule a task for it at a certain fixed rate, using the method
scheduleAtFixedRate
. The problem is that after some actions, i want to finish/cancel this task that was scheduled before.

I know that i can use
.cancel()
or
.purge()
but that will cancel/finish my timer, which is something that i don't want to. I just want to finish the task.

Does any of you know how to do this ?

This is my code (I have the
Timer
created as a field of the class)

receiveTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {

int fileSize=(int)fileSizeToReceive;
int actual= totalReceived;

((Notification.Builder) mBuilderReceive).setContentText("Receiving "+actualNameToReceive);
((Notification.Builder) mBuilderReceive).setProgress(fileSize, actual, false);
mNotifyManager.notify(id, ((Notification.Builder) mBuilderReceive).getNotification());
}
},0,500);//delay, interval

Answer

Just hold a reference to your TimerTask so you can call cancel() on it whenever you'd like.

Calling cancel() on the TimerTask will not stop the Timer.

For example:

TimerTask task;

// ...

// initialize the TimerTask and schedule it
task = new TimerTask() {
    @Override
    public void run() {
        int fileSize=(int)fileSizeToReceive;
        int actual= totalReceived;

        ((Notification.Builder) mBuilderReceive).setContentText("Receiving  "+actualNameToReceive);
        ((Notification.Builder) mBuilderReceiver.setProgress(fileSize, actual, false);
        mNotifyManager.notify(id, ((Notification.Builder) mBuilderReceive).getNotification());
    }
};

receiveTimer.scheduleAtFixedRate(task, 0, 500);

// ...

// calling cancel() on the TimerTask instance will effectively stop it
// without stopping the Timer
void stopTask() {
    if(task != null) {
        task.cancel();
        task = null;
    }
}