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.