【问题标题】:Possible solution for avoiding memory leak from static context reference避免静态上下文引用引起内存泄漏的可能解决方案
【发布时间】: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


    【解决方案1】:

    您应该明确删除 onPause()onStop() 中的引用,而不是 onResume() 中的引用。
    这样做应该会删除对您的活动的所有引用,从而防止内存泄漏。

    【讨论】:

    • 嘿。对不起这是我的错。在公共汽车上输入问题...意味着在onPause() 中有disconnect()。以上已更正。有了这个更正,这是否意味着我的方法正在做它应该做的事情来避免泄漏?
    • 是的,我很确定。
    • 虽然我建议不要清除完整的arrayList,但如果您的实例列表在应用程序上下文中,则只清除当前实例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 2015-09-01
    相关资源
    最近更新 更多