I have gone through the article http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html. In this article it is suggested to use a static inner class with a WeakReference . Many inner classes are used for event listeners. Can those inner class also cause memory leaks? Should those inner class be static?
1 Answers
Can those inner class also cause memory leakage?
Possibly. It depends on what those listeners are registered upon.
For example, a well-written OnClickListener
for a Button
should not result in a memory leak, because even though the OnClickListener
may be an inner class and have an implicit reference to the Activity
, the whole set of objects are all just tied to the activity. Hence, when the activity is destroyed, the activity, Button
, and OnClickListener
can all be garbage-collected as a whole.
However, a LocationListener
, registered with the LocationManager
system service, is held by the process. Hence, even if the activity is destroyed, the listener will remain registered. If that listener is an inner class, it will continue to hold an implicit reference to the activity, and you will have a memory leak.
Should those inner class be Staic one?
Possibly. In most cases, the right answer is "if you are registering a listener other than with the UI, be sure to unregister it at an appropriate point". In that case, there will be no leak.
Can any one give me any example code how the event listener can use leak-proofly.
Not in the abstract, no.

- 986,068
- 189
- 2,389
- 2,491
-
Here is a simple listener that causes memory leak http://stackoverflow.com/questions/7083441/android-alertdialog-causes-a-memory-leak – user4o01 Feb 09 '14 at 19:25
-
How can I know if the Listener is tied to the activity or held by the process? – JaskeyLam Sep 11 '14 at 03:12
-
If my listener is holding a reference to the context of an activity. I set this listener in my adapter. And somehow, LeakCanary accused a memory leak. What could it be? I'm a little confused... – EduardoMaia Dec 12 '17 at 17:59
-
@EduardoMaia: I suggest that you ask a separate Stack Overflow question, where you provide a [mcve]. – CommonsWare Dec 12 '17 at 18:25