0

I am developing an application, In which I am sending the device location to the server for every one min. I am using Handler here to schedule my task. After User click the STOP button, the handler should stop its execution. I am unable to achieve this. Please find my code below.

    public void callSpecficTime() {

    timer = new Timer();
    doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {

            handler.post(new Runnable() {
                public void run() {
                    try {
                        Log.e("TImeOnSchedule", String.valueOf(inTime));
                        if(inTime==5)
                        {
                             new PostDataAsyncTask().execute();
                         }


                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 60000);
}

StopTask code :

    public void stopTask(){

    if(doAsynchronousTask!=null){
        Log.d("TIMER", "timer canceled");
        handler.removeCallbacks(doAsynchronousTask);
     // timer.cancel();
        doAsynchronousTask.cancel();
    }

}

I tried stopService,removeCallbacks but it didn't work. Can anyone provide me solution for this?

UPDATED

 public void onClickButton(View v)
{
    if(v.getId()==R.id.IBstart)
    {
        callAsynchronousTask();
        callSpecficTime();
    }
    else if(v.getId()==R.idIBstop)
    {
       stopTask();
    }
}

This is ** callAsynchronousTask()**

 public void callAsynchronousTask() {
    new PostDataAsyncTask().execute();
}

I am posting data twice. First time is when User click the START button and then I am start the timer to execute for every one min.

Anish Kumar
  • 478
  • 4
  • 12
  • 27

2 Answers2

0

use purge() after cancel();

public void stopTask(){

    if(doAsynchronousTask!=null){
        Log.d("TIMER", "timer canceled");
        handler.removeCallbacks(doAsynchronousTask);
     // timer.cancel();
        doAsynchronousTask.cancel();
        doAsynchronousTask.purge();
    }

}
Miguel Benitez
  • 2,322
  • 10
  • 22
0
  1. You should stop the TimerTask first with: Timer.Cancel() and Timer.Purge().
  2. you can change: handler.removeCallbacks(doAsynchronousTask); to removeCallbacksAndMessages(null).

Edit:

Look at your schedule code: timer.schedule(doAsynchronousTask, 0, 60000); --> that means you start your task immediately and repeated it after 60s.
When I see your onClickButton listener, there are 2 tasks which will be executed immediately. As a result, you cant cancel the tasks which are executed. To avoid it, you can call: timer.schedule(doAsynchronousTask, 60000, 60000);

Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86