Maksim Dmitriev Maksim Dmitriev - 9 months ago 39
Java Question

An anonymous runnable prevents Android from garbage-collecting the activity in which it's defined

While reading the example, I noticed that the author created

Runnable task
. If I close the activity, the system won't be able to garbage-collect it because the runnable contains an implicit reference to MyActivity, right? The activity will be alive as long as the runnable works.

Please correct me if I'm wrong.

Answer Source

Seems correct.

From your link (although talking about AsyncTask, not anonymous Runnable):

if it is an inner class of your Activity/Fragment, it holds an implicit reference to it, which is bad practice, because Activity/Fragment can be destroyed on configuration change, but they will be kept in memory while worker thread is alive; if it is declared as standalone or static inner class and you are using reference to a Context to update views, you should always check whether it is null or not"