I'm having the same situation as here: Android AsyncTask won't stop when cancelled, why?
I set a timer to kill the AsyncTask after a couple of seconds. It works perfectly on android 2.3.5 (the task is cancelled after the timeout I set), but for some reason it doesn't work on Android 4+)
This is the relevant code (all inside the AsyncTask class)
private class TaskKiller extends TimerTask {
private AsyncTask<?, ?, ?> mTask;
public TaskKiller(AsyncTask<?, ?, ?> task) {
mTask = task;
}
public void run() {
mTask.cancel(true);
}
}
@Override
protected String doInBackground(Void... nothing) {
// Setting the Task timeout.
Timer timer = new Timer();
timer.schedule(new TaskKiller(this), 3000);
response = HttpRequest(url); // this method makes an HttpPost request.
// This, I think, is where android 4+ is unable to cancel the task (while making the http request). It is perfectly cancelled in 2.3.5, though.
}
@Override
protected void onCancelled() {
Log.e("TASK CANCELED","...");
}
It's working like a charm in android 2.3.
Do you have any clue on How to make it work in android 4+?