AsyncTask.execute() runs callback after onDestroy is called AsyncTask.execute() runs callback after onDestroy is called sqlite sqlite

AsyncTask.execute() runs callback after onDestroy is called


AsyncTask within the activity may not be the best solution for running the background task, as it holds a reference to the activity, which is now destroyed.

You could consider using a Fragment with setRetainInstance(true) to do your background work with an AsyncTask, or an IntentService.

See here for how to use a task fragment to do your background work.


What you are seeing is memory leaking - the AsyncTask retains a reference to the Activity it was declared in and is preventing the Android runtime from garbage collecting it. To answer your questions:

  1. AsyncTask cannot be stopped with a command. You can request to cancel it in onDestroy() but it will still do it only after the doInBackground() method has executed which in your case will be the Runnable.

  2. You have the option of using a static nested AsyncTask which will not hold a reference to the Activity it resides in - the caveat is that you will not be able to reference anything from the Activity but that shouldn't be a big problem for your case.


An AsyncTask can survive orientation changes if you put it in a retained fragment. See Handling Configuration Changes with Fragments. If you want the task to survive when the activity finishes or goes into the backstack, put it in a Service.