0

I have a class name is GetData that extends from AsyncTask. In other class I have an object from GetData and with this codes I use that:

GetData getData = new GetData();
getData().execute();

I want to stop this thread when a button clicked. I do this with:

getData().cancel(true);

I want to know if I canceled thread while it is in doInBackground, it stopped or it goes to onPostExecute and then stop?

Behrooz Fard
  • 536
  • 4
  • 26
  • https://stackoverflow.com/questions/2735102/ideal-way-to-cancel-an-executing-asynctask – Goku Nov 16 '17 at 06:56

2 Answers2

0

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

For further details visit:

https://developer.android.com/reference/android/os/AsyncTask.html

Just like:

onPostExecute(Result result)
{
}

you can override a method for cancel to update your UI accordingly when your asyncTask is cancelled as follows:

onCancelled(Result result)
{
    // here you can handle situation according to your requirements
}

So point of your interest here is that whenever you cancel your task before it enters into onPostExecute it will not go into onPostExecute but will jump to onCancelled. You can also call task.cancel(true); in postExecute according to your condition by applying required checks.

Muhammad Saad Rafique
  • 3,158
  • 1
  • 13
  • 21
-1

From the Android documentation:

Calling this method will result in onCancelled(Object) being invoked on the UI thread after doInBackground(Object[]) returns. Calling this method guarantees that onPostExecute(Object) is never invoked.

So onPostExecute will not be called.

parkgrrr
  • 738
  • 7
  • 12