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.
}