Android:由于成员变量导致内存泄漏



我开发了一个Android应用程序,它由一个FragmentActivity和几个在选项卡更改时调用的片段组成。每个片段都与一个视图相关联。片段的逻辑被封装在单独的类中。班上做了一些复杂的计算。这些计算的结果将显示在片段视图的几个文本视图中。进一步的碎片视图包含一个停止按钮,类的计算将在单击停止按钮时做出反应。

我现在的问题是如何组织对类中那些视图成员(文本视图和停止按钮)的访问。安全吗将与每个文本视图关联的变量作为成员变量传递给相应的类?这是我使用的相应代码。

class ClassAFragment extends Fragment 
{
    ClassA classA;
    ...
    public View onCreateView(...) 
    {
        Button stopButton = (Button) this.getActivity().findViewById (R.id.btnStop);
        TextView timeLabel = (TextView) this.getActivity().findViewById (R.id.mTimeLabel);
        this.classA = new ClassA();
        this.classA.setAppElements(timeLabel, stopButton);
    }
    ...
}
class ClassA 
{
    TextView mTimeLabel;
    Button mStopButton;
    public void setAppElements(TextView timeLabel, Button stopButton) 
    {
        this.mTimeLabel = timeLabel;
        this.mStopButton = stopButton;
        this.mStopButton.setOnClickListener (this.mStopListener);
    }
    private void showCurrentProgress() 
    {
        this.mTimeLabel.setText("some text");
    }
    public void stop() 
    {
        // react upon stop button being clicked
    }
    OnClickListener mStopListener = new OnClickListener ()
    {
        @Override
        public void onClick (View v)
        {
            ClassA.this.stop ();
        }
    };
    ...
}

对于内存泄漏,该代码是否安全?在Android的官方文档中,我读到你不应该将绑定到应用程序上下文的任何对象传递给成员变量(处理运行时更改)。

您可以使用LocalBroadcastManager或Bus(例如Otto EventBus)来通知UI(在您的情况下是Fragment)。LocalBroadcastManager更快(然而,Bus使用反射,这在ICS之前的Android版本中没有,而且可能更慢),但Bus更简单。希望能有所帮助。

附言:永远不要在UI碎片上设置setRetainInstance(true)。

p.p.S如果你这样做了-确保你在onDestroy()中正确地释放了视图

他们谈论的是如果在片段中使用setRetainInstance(true);并向其传递对与上下文关联的任何其他对象的引用,则可能会遇到的问题。setRetainInstance(true);意味着当"活动"被销毁时,片段不会被销毁,因此,如果将对视图的引用传递给它并销毁"活动",这将导致内存泄漏,因为视图不会被垃圾收集。

最新更新