【发布时间】:2014-02-17 02:52:44
【问题描述】:
我知道内存泄漏在堆栈溢出时几乎已经完成,但这里还有另一个问题,只是为了确定......
我有一个单例类MyManager,它会在某某事件中通知听众某些事情发生了变化。该管理器管理一些“全局”数据结构,因此我使用它。
public final class MyManager{
private final static MyManager INSTANCE = new MyManager();
private ArrayList<MyManagerListener> mListeners = new ArrayList<MyManagerListener>();
public static void addListener(MyManagerListener l){
if (!INSTANCE.mListeners.contains(l)) INSTANCE.mListeners.add(l);
}
public static void disconnect(){
// Does calling this in Activity's onPause() avoid memory leak?
INSTANCE.mListeners.clear();
}
/// Implementation of Manager stuff which includes call to mListener.doSomething();
}
那我当然有接口MyManagerListener:
public interface MyManagerListener{
public void doSomething();
}
然后在我的 Activity 中,我将 Activity 实例添加到经理的mListeners,据我了解,这是创建对 Activity 的静态引用,可能会破坏 Activity 的生命周期,这很糟糕。
public class MainActivity extends Activity implements MyManagerListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create potential memory leak here.
MyManager.addListener(this);
...
}
protected void onPause(){
super.onPause();
// does calling this fix the potential memory leak?
MyManager.disconnect();
}
@Override
public void doSomeThing(){
//do something
}
}
我的问题是,我加入 MyManager.disconnect() 是否解决了潜在问题?我知道调用ArrayList.clear() 会将列表底层数组中的所有对象设置为null
【问题讨论】:
标签: android android-activity memory-leaks android-context