Search code examples
androidsqliteandroid-activityandroid-asynctaskactivity-lifecycle

AsyncTask.execute() runs callback after onDestroy is called


I am saving data on onPause method to SQLite database.

  • I call myObject.saveEntry(data).
  • It saves data by calling AsyncTask.execute(new Runnable(){})
  • Once data is saved, the callback method savedSuccess(message) is called
  • An Activity method showMessage(message) is called
  • A toast is shown saying the data is saved successfully

My doubt is on how to handle the orientation changes. When the orientation changes,

  • onPause is called and saveEntry method is called.
  • After that onDestroy is called
  • A new instance of the Activity is created again.
  • The savedSuccess(message) method callback gets executed now (which was called from the previous instance of the Activity)
  • showMessage(message) is called and toast is shown

My questions are

  1. Should I stop the AsyncTask from executing in the onDestroy method
  2. If not, how should I handle such situations when Activity gets destroyed before the database save/update/delete is complete?

Solution

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