3

On the long run, AsyncTask produces a memory leak : if the AsyncTask lasts for long, it keeps the activity "alive" whereas Android would like to get rid of it as it can no longer be displayed. The activity can't be garbage collected and that's a central mechanism for Android to preserve resources on the device.

Does that means that if we call finish() method and asynctask is running then also activity will remain "alive"?If not,then what does this means

if the AsyncTask lasts for long, it keeps the activity "alive"?

Activity will be alive unless we call finish() method or we press back button.Does this mean that if asyntask is running then activity will be alive even after that?

user3684678
  • 451
  • 3
  • 7
  • 20
  • I am not really sure, but my understanding is, that the activity will stay alive as long as the asyncTask is running and the system doesn´t finish it automatically. The android system is a "self-cleaning" mechanism which kills not used apps or even running apps if resources are needed urgently. BUT if You finish the activity, I think the activity is destroyed because You call it directly by yourself and not from the system. If You press back button, the activity is usually not destroyed, unless You are calling finish() in onBackButtonPress(). – Opiatefuchs Mar 16 '16 at 06:41

1 Answers1

11

If an AsyncTask is declared as a non-static inner class inside an activity, that means it always holds a strong reference to the enclosing outer class where it was created. So, as long as the AsyncTask is running, it holds this strong reference to the activity, which means it will not be garbage collected even after finish() is called and onDestroy() executes. This is a very common problem with AsyncTask that are not properly implemented to prevent this.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441