If I keep a WeakReference
of an activity in AsyncTask
, will my application object remain alive or will it be garbage collected?
-
you can check it https://stackoverflow.com/questions/44309241/warning-this-asynctask-class-should-be-static-or-leaks-might-occur. it may help – Linh Apr 04 '18 at 08:54
-
There is no clear answer on this part. Let's say I have App A, Activity B, Async C. If Async C has a WeakReference of B, does that keep an Application object in A alive or can that be garbage collected? – grad9 Apr 04 '18 at 09:01
-
do you know what a WeakReference is? – Tim Apr 04 '18 at 11:57
-
@TimCastelijns + more info, the context/timing of operation, in the question is, when an activity has been closed/or closing, however, async is still running, further, it is only a single activity app. – grad9 Apr 05 '18 at 01:38
1 Answers
I am assuming that when you say "my application object" you mean the instance of android.app.Application
(which may or may not be a subclass depending on your particular AndroidManifest.xml
).
The Application
instance for an Android app will never be garbage collected, ever. While your app is running there is a single instance of the Application
class. The root reference comes from the ActivityThread
which is the main thread of your app. The ActivityThread
enters Looper.loop()
and never returns.
When the Android system decides your app becomes an "old" cached process and isn't needed any more then will it be terminated. In that case it doesn't bother letting the ActivityThread
return so the Application
instance won't be garbage collected, it will simply be erased when your process stops.
A new Application
instance will be created the next time Android starts your app.
Thus keeping a WeakReference
to an Activity
has no effect on the Application
instance, as long as your process is running the Application
instance is available. You may safely keep a reference to the Application
instance anywhere and access it any time you like, see Get Application instance from static method for an example. Alternatively call Context#getApplicationContext()
and save that for later if needed.

- 13,927
- 5
- 80
- 123