0

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+?

Community
  • 1
  • 1
Dandy
  • 303
  • 5
  • 14

1 Answers1

1
private HttpUriRequest mRequest;


protected String doInBackground(Void... nothing) {
    ...
    mRequest = new HttpGet(url); // or HttpPost
    response = client.execute(mRequest);
    ...
}

private void myCancelationRoutine() {
      mRequest.cancel();
      mTask.cancel();
}
Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158
  • Good idea. I didn't think of if. Unfortunately, eclipse is showing an error and requests me to "Add Cast" to mRequest (it adds a Timer cast!). So it doesn't work, so far. I'll test similar approaches and get back. – Dandy Jun 26 '13 at 19:03
  • The solution was simple. Instead of "mRequest.cancel()" I had to use mRequest.abort(), and it worked. Thanks for this simple and bright solution. – Dandy Jun 26 '13 at 20:24