Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Asynctask is running will activity will be alive even after finish() method?

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?

like image 446
user3684678 Avatar asked Dec 06 '25 10:12

user3684678


1 Answers

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.

like image 114
Doug Stevenson Avatar answered Dec 07 '25 23:12

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!