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:
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.