Friday, September 21, 2012

Kill Android AsyncTask if it hangs



I have an AsyncTask in my Android App that makes a network call. It may happen that the call for ever stuck. So I need a solution to handle this issue.


First I create a TimerTask that call cancel() to my AsyncTask:


class TaskKiller extends TimerTask {
private AsyncTask<?, ?, ?> mTask;
public TaskKiller(AsyncTask<?, ?, ?> task) {
this.mTask = task;
}

public void run() {
mTask.cancel(true);
}
}


Then I use this TimerTask with a timeout I need:


protected Boolean doInBackground(Object... params) {
Timer timer = new Timer();
timer.schedule(new TaskKiller(this), TIMEOUT);

// do some stuff, network, what ever can hangs
 // ...
// cancel the task if all things are done

timer.cancel();
}


onCancelled() will be called if your stuff needs longer than your timeout:

protected void onCancelled() {
// do something, inform user etc.
}

4 comments:

  1. Thank you so much! I was looking for an easy to follow tutorial on AsyncTask and this was just perfect :D

    ReplyDelete
  2. nice and easy! Thank you!

    ReplyDelete
  3. Buen aporte ! Gracias

    ReplyDelete