You should stop all the tasks manually. Activity lifecycle won't take care of your tasks automatically.
You should manage all the tasks in somewhere(I suggest Activity or Fragment, not in ListView). Gather all the tasks in list and stop'em on onDestroy(or onPause depending your situation).
public MyActivity extends Activity {
private ArrayList<SomeTask> mTasks;
private void startTasks() {
SomeTask task = new SomeTask();
task.execute();
mTasks.add(task);
}
@Override void onDestroy() {
for (SomeTask task : mTasks) {
tasks.cancel(true);
}
}
private class SomeTask extends AsyncTask<Void, Void, Void> {
private MyListItem mItem;
private int mIndex;
public SomeTask(MyListItem item, int index) {
mItem = item;
mIndex = index;
}
protected Long doInBackground(Void... urls) {
// do whatever you want
return null;
}
protected void onPostExecute(Void result) {
// update your adapter here
}
}
}
Sadly, AsyncTask won't just stop even if you call task.cancel(true).
You also have to check if the task is cancelled inside the AsyncTask.
Below is a sample taken from AsyncTask reference page:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Checkout Cancelling a task section for more information.