0

I am trying to stop Asynctask from Timer but it is not stopping. Here is code where I schedule the timerTask(asynctask)

public void CreateTimer(){
    timer =new Timer();
    timerTask = new MyTimertask();
    timer.schedule(timerTask,5000,2000);
}
Peter Walter
  • 993
  • 6
  • 11

2 Answers2

0

The documentation for TimerTask doesn't seem to have the schedule method. You can cancel an AsyncTask with cancel(true). Maybe instead you could use a CountdownTimer or a new Thread?

With CountdownTimer:

CountDownTimer cdt = new CountDownTimer(5000, 1000) {
        @Override
        public void onTick(long l) {}

        @Override
        public void onFinish() {
            cancel();//Cancel CountdownTimer
            cancel(true);// Cancel Asynctask
        }
    };
    cdt.start();

With Thread:

Thread thread = new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(5000);
                    cancel(true);//Cancel Asynctask
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        };
thread.start();
-1

Async task can be cancelled at any time by invoking cancel(boolean). More information can be found here.

It would be helpful if you post your code to give a more precise answer.

Sudhin Philip
  • 644
  • 8
  • 15