I followed "Avoiding Memory Leaks" article from here.
However the proposed solution does not solve the leak problem. I tested this with android emulator on Windows XP (SDK 2.3.1). I dumped the heap and checked the main activity is still in the heap (I used MAT)
Here's what I did:
- create HelloWorld app with HelloWorldActivity (it has no child views)
- run Emulator and launch HelloWorld app.
- close it by clicking back-key.
- Cause gc in DDMS and dump heap <-- Here I found HelloWorldActivity instance.
- 'Path to GC Roots' from it shows the following path.
HelloWorldActivity <- PhoneWindow$DecorView <- InputMethodManager
InputMethodManager is a singleton and three references to DecorView which references HelloWorldActivity.
I can't understand why InputMethodManager still references DecorView instance even after the activity is destroyed.
Is there any way to make sure that the main activity is destroyed and GC-able after closing it?
It seems that calling InputMethodManager's methods 'windowDismissed' and 'startGettingWindowFocus' do the stuff.
Something like this:
Reflector's code:
If I understand your question correctly, the answer is: no, you cannot make sure the activity is gc'ed. Your activity's onDestroy() method should have been called and the activity shut down. That does not mean, however, that the process is killed or that the activity is gc'ed; that's managed by the system.
I have noticed that some listeners tend to keep a reference to the activity under some circumstances, even after the activity supposedly has been finished. A rotation from portrait to landscape can, for example, restart your activity and if you're unfortunate your first activity is not gc-ed properly (in my case due to some listeners still holding a reference to it).
Being a former C/C++ programmer I have it implanted in my spine to "un-set" any listeners in Activity.onDestroy() (
setXyzListener(null)
).EDIT:
Just as Ted commented below, one should indeed "set" and "un-set" listeners in
Activity.onResume()
andActivity.onPause()
respectively.