Android 内部类由于 this$0 变量而未被垃圾回收
我是 Android 的初学者,但我似乎遇到了一个问题,我的 Activity 永远不会被垃圾收集,因为在我的线程的非静态内部类中仍然有一个对 Activity 的引用,该变量称为 this$0 我通过使用Eclipse中的MAT找到它。以下是我当前的设置。
public class MyActivity
-->class MySurfaceView
---->class MyThread
当试图查找有关是否可以删除最后一个实例的信息时,在找到一篇非常有用的文章 此处。
如果您不控制,请避免在活动中使用非静态内部类 他们的生命周期,使用静态内部类并进行弱引用 到里面的活动。解决这个问题的方法是使用静态 具有对外部类的 WeakReference 的内部类,如以下所示 以ViewRoot及其W内部类为例
所以看来我不应该使用这个内部类系统或使用 WeakReferences。
我的问题是,为什么示例项目使用没有弱引用的内部类系统?他们还在收集垃圾吗?或者它们的设计目的不是处理垃圾收集?
我的应用程序是否可能存在代码问题,这意味着我应该更正我的代码并仍然保留我的内部类?或者我应该分离这些类(或引入 WeakReferences)?
I am a beginner to Android but I seem to be running across a problem where my Activities are never being garbage collected because there is a still a reference to the Activity in the non-static inner class of my thread the variable is called this$0 I found it by using the MAT in Eclipse. Below is my current setup.
public class MyActivity
-->class MySurfaceView
---->class MyThread
When trying to find information on if it was possible to remove this last instance it appears I can't after finding a very useful article here.
Avoid non-static inner classes in an activity if you don't control
their life cycle, use a static inner class and make a weak reference
to the activity inside. The solution to this issue is to use a static
inner class with a WeakReference to the outer class, as done in
ViewRoot and its W inner class for instance
So it seems like I shouldn't use this system of inner classes or use WeakReferences.
My question is, why do the sample projects use the inner class system with no WeakReferences? Are they still garbarge collected? Or were they designed not to deal with garbage collection?
Is it likely my application has a code problem, meaning I should correct my code and still keep my inner classes? Or should I seperate the classes (or introduce WeakReferences)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用内部类使其静态并具有弱引用父级。
还将长期存在的对象存储在应用程序上下文中。
You can use inner classes make them static and have a Weak Reference the parent.
Also store long living objects in Application Context.