Memory leakage in event listener

后端 未结 1 1309
渐次进展
渐次进展 2021-01-30 17:40

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 Wea

相关标签:
1条回答
  • 2021-01-30 18:05

    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.

    0 讨论(0)
提交回复
热议问题