在事件侦听器的内存泄露 [英] Memory leakage in event listener
问题描述
我已经通过文章<一个走了href="http://developer.android.com/resources/articles/avoiding-memory-leaks.html">http://developer.android.com/resources/articles/avoiding-memory-leaks.html 。在这篇文章中,建议使用静态内部类与弱引用。许多内部类中使用了事件侦听器。这些内部类也可能导致内存泄露?如果这些内部类是Staic吗?任何一个可以给我任何例如code怎样事件侦听器可以使用泄漏proofly。
可以将这些内部类也可能导致内存泄露?
可能。这要看这些侦听器后注册。
例如,一个精心编写的 OnClickListener
为按钮
不应导致内存泄漏,因为即使虽然 OnClickListener
可能是一个内部类,并有一个隐含的引用活动
,整套的对象都是只是绑在活动。因此,当活动被破坏,活动,按钮
和 OnClickListener
都可以被垃圾回收作为一个整体
然而,一个 LocationListener的
,与 LocationManager
系统服务注册,由工艺举行。因此,即使该活动被破坏,听者会保持注册。如果该侦听器是一个内部类,它会继续持有暗示了活动,你将有内存泄漏。
如果这些内部类是Staic一个?
可能。在大多数情况下,正确的答案是:如果你是注册监听器比与UI等,确保在适当的时候给它注销。在这种情况下,将不会有泄漏。
任何一个可以给我任何例如code怎样事件侦听器可以使用泄漏proofly。
不是在抽象的,没有。
I have gone through the article http://developer.android.com/resources/articles/avoiding-memory-leaks.html . In this article it is suggested to use static inner class with Weak Reference . Many inner class are used in the event listeners. Can those inner class also cause memory leakage? Should those inner class be Staic one? Can any one give me any example code how the event listener can use leak-proofly.
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.
这篇关于在事件侦听器的内存泄露的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!