为什么在 GC 中清除来自视图的引用,而当包含 Activity 被销毁时,来自嵌套内部 class 的引用仍然存在?

Why in GC the references from Views are cleaned, while the references from nested inner class remain when the containning Activity is destroyed?

我已经阅读了很多关于内存泄漏的文章。他们都告诉我,如果 Activity 包含(非静态)嵌套内部 class 或(非静态)匿名内部 class,那么 Activity 可能不会当它被销毁时被垃圾收集清理,因为(非静态)嵌套内部 class 包含对其外部 class 的引用(即 Activity)。他们还建议我应该尽可能使用 static inner class(所以我必须将所有嵌套的 inner classes 更改为 static classes,非常糟糕的做法)

但我不明白,为什么 View 对象的引用不会阻止它们包含的 Activity 被清除?在我看来,来自视图的引用和来自嵌套内部 classes 的引用在同一个 Activity.

中并没有太大区别

问题不在于 具有 非静态内部 class 或匿名 class。这不是问题。 GC 可以很好地处理循环引用,它会检测到 inner/anonymous class 引用了 Activity 并且它会清理所有内容。没问题。

问题发生在 当您在静态变量中存储对非静态 inner/anonymous class 的引用时,或者如果您将引用传递给另一个组件该引用。在这些情况下,Activity 无法被垃圾回收,因为仍然有一个 活动对象或静态变量 包含对 inner/anonymous [=27= 的引用].

不幸的是,许多关于内存泄漏的警告文章不正确、不完整或不够详细,无法准确描述问题。