【问题标题】:Is having a managed static reference to a Fragment or Activity ok?对 Fragment 或 Activity 进行托管静态引用可以吗?
【发布时间】:2016-11-14 11:21:09
【问题描述】:

我想知道是否对FragmentActivity 进行托管静态引用可以吗?托管我的意思是释放相关生命周期回调的静态引用。请考虑以下代码:

public class StaticReferencedFragment extends Fragment {

    public static StaticReferencedFragment instance;

    public StaticReferencedFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_static_referenced, container, false);
    }

    @Override
    public void onStart() {
        super.onStart();
        instance = this;
    }

    @Override
    public void onStop() {
        super.onStop();
        instance = null;
    }
}

我是否有泄露Fragment/Activity 对象的风险?

【问题讨论】:

  • 不,不是。它总是闻起来像糟糕的设计
  • 你为什么需要这个
  • @Blackbelt 出于好奇,详细说明一下。为什么这是个坏主意?
  • @TimCastelijns 我只是在问。有时访问该死的东西很方便。

标签: android android-fragments android-activity memory-leaks


【解决方案1】:

我会冒泄露 Fragment/Activity 对象的风险吗?

是的。例如,您的片段可见时未处理的异常将绕过您的生命周期方法并导致您无法在static 字段中使用null

除此之外,还不清楚这会给你带来什么:

  • 托管此片段的活动可以简单地在常规字段中保持片段

  • Activity 中的其他 Fragment 不应该知道也不关心这个 Fragment 的存在(Fragment 应该关心自己和它们的 Activity,而不是 Peer Fragment)

  • 其他组件,如服务和其他线程,应该既不知道也不关心整个活动的存在,更不用说这个片段(使用事件总线或其他松散耦合的通信模式)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-09
  • 2013-05-13
  • 1970-01-01
相关资源
最近更新 更多