user1471575
user1471575

Reputation: 741

android: cancel(true) does not kill the AsyncTask

I am using an Android AsyncTask in order to download files from a server. when files are downloaded, I am trying to kill the AsyncTask.

protected void onPostExecute(Void result) {
    MyTask.cancel(true);
}

But it stills running (I can see it from the Debug window in eclipse). How to kill the AsyncTask?

Upvotes: 3

Views: 6408

Answers (2)

Abner Niu
Abner Niu

Reputation: 405

There is some documentation from here about canceling an AsyncTask, which may be relevant:

A task can be cancelled at any time by invoking cancel(boolean).

Invoking this method will cause subsequent calls to isCancelled() to return true.

After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.

To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)"

Upvotes: 2

DeeV
DeeV

Reputation: 36035

When the AsyncTask is finished running, onPostExecute() will be called. The thread will die. The garbage collector will clean it up. You don't have to do anything. What you're doing is redundant.

Other than that, calling "Cancel" sends and interrupt signal to the thread. If your process can be interrupted, it will stop blocking and continue to execute. You then have to call isCancelled() in doInBackground() and return from the method if isCancelled() is true. After which, onCanceled() and onPostExecute() will be called and the thread will die on it's own like normal.

Upvotes: 3

Related Questions