【发布时间】:2018-01-10 01:19:13
【问题描述】:
为了避免内存泄漏,我编写了以下方法,该方法将用于活动,主要用于片段(使用继承)。该方法应该允许我永远不会通过调用
直接引用活动//this or getActivity()
方法是:
private WeakReference<BaseActivity> activityWeakReference = null;
public BaseActivity getActivityFromWeakReference(){
activityWeakReference = activityWeakReference == null ?
new WeakReference<BaseActivity>((BaseActivity)getActivity()) :
activityWeakReference;
return activityWeakReference.get();
}
根据内存泄漏威胁调用此方法getActivityFromWeakReference() 而不是getActivity() 是否安全?
如果这样做不安全,我是否应该返回 activityWeakReference 并改为调用其 get() 方法以确保安全?
我一直在多个片段中使用它,到目前为止我还没有遇到任何问题。我问这个问题是因为我读到了这个(here):
只要助手的生命周期在
Activity,则无需使用WeakReference。如果帮手 可以比Activity寿命更长,那么你应该使用WeakReference避免在系统运行时在对象图中保留Activity摧毁它。
到目前为止,我还没有遇到过引用元素比活动更长寿的情况。如果您发现错误或可能的错误,请把它写在 cmets 中。
【问题讨论】:
-
请注意,当
activityWeakReference不为空,但activityWeakReference.get()为空时,您的方法可能返回空。 -
@Mateus Gondim,感谢您的输入,我在使用前已经检查了 null。
标签: java android memory-leaks weak-references