I have this AsyncTask:
private class GetMyFlights extends AsyncTask<String, Void, Integer> {
private ProgressDialog dialog;
public GetMyFlights(ListActivity activity) {}
@Override
protected Integer doInBackground(String... params) {
return getData();
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
//...
}
}
When I change to another activity I want to stop it. So I set this:
@Override
protected void onPause() {
if(mGetMyFlights != null){
mGetMyFlights.cancel(true);
Log.d(TAG, "MyFlights onPause, cancel task");
}
super.onPause();
}
But the code inside getData is still working when I change my activity. How can I be sure is stop?
What I usually do is call
cancel(true)on theAsyncTaskinstance and checkThread.interrupted()indoInBackground. You could checkisCancelled(), but that doesn’t work if the actual work is done in some other class that is independent from yourAsyncTaskand doesn’t know about it. For example (copied directly from my owngetData()method, inside myDataclass, independent from any activities, async tasks, etc.):Just make sure to handle the
InterruptedExceptionin yourdoInBackground(), e.g.:Also worth noting that
onPostExecute()is not called if the task is cancelled. Instead,onCancelled()is called.