android - 使用弱引用是避免内存泄漏的最佳方法吗?

标签 android performance memory-management mvp

最近我看到一个博客,其中讨论了在 android- https://medium.com/google-developer-experts/weakreference-in-android-dd1e66b9be9d 中避免弱引用。

目前,我正在从事的项目遵循 MVP 架构,我们在演示者中使用弱引用(用于听众)来处理各种回调事件。但是,我正在寻找替代方法而不是使用弱引用。 ..可能是我设计应用程序架构以避免此类内存泄漏问题的更好方法。 这里的问题是:-

我当前使用的方法是否对演示者中的各种听众使用弱引用有害...?

最佳答案

Is the current approach which I am using i.e using weak references for various listeners in presenter harmful...??

也许吧。如果不深入研究您的代码库,很难具体地说。话虽如此,您需要考虑使用 Wea​​kReferences 的一般缺点。我会给你指向另一个 StackOverflow answer这很清楚:

... using WeakReference not just solve one problem ("I should keep in mind to not forget to remove added listener somewhere"), but also rise another -- "I should keep in mind what my listener ca stop listen in any moment when where is no more reference to it". You not solve problem, you just trade one problem for another. Look, in any way you've forced to clearly define, design and trace livespan of you listener -- one way or another.


If so..than how I can solve this problem in a much better way.?

慢慢开始挑选您对 WeakReferences 的使用。删除它们。使用 Android 提供的生命周期事件为您带来好处,并在正确的时间附加、分离。最后,添加 LeakCanary到你的工具箱。使用它,检查各种 Activity 和 Fragment 的生命周期,以查看何时何地发生泄漏。

关于android - 使用弱引用是避免内存泄漏的最佳方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40967901/

相关文章:

java - 如何将 Hashmap 转换为 String 以保存在 SQLite 数据库中?

java - 尝试运行 OpenCV 教程 2 - 混合处理演示

android - 尝试调用虚方法

iphone - iPhone OS 应用程序的可用内存

c - 查找进程内存中未使用的内存

Android Studio 和 Dexguard

php - 带宽与数据库查询

c# - LINQ优化的问题

ruby-on-rails - 在 Rails 应用程序中跟踪事件时忽略机器人

python - 使用 C 扩展 python 时查找内存泄漏