记一次Fragment的内存泄露

最近遇到一个内存泄露, 代码非常简单 :

先打开一个 FragmentA, 然后通过 replace 替换成 FragmentB, 并且加入回退栈, 因为 FragmentB 关闭后还要回到 FragmentA. 伪代码如下

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentA fragmentA = new FragmentA();
        replaceFragment(R.id.frame, fragmentA);
    }
    
    //replaceFragment 并加入回退栈
    public void replaceFragment(int containerID, Fragment fragment) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(containerID, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }
}
public class FragmentA extends Fragment {
    private Button mButton;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragmenta, container, false);
        mButton = view.findViewById(R.id.btn_a);
        mButton.setText(MessageFormat.format("{0}{1}", mButton.getText().toString(), getArguments().getInt("index")));
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //将 FragmentA 替换成 FragmentB,并且加入回退栈
        mButton.setOnClickListener(v -> {
            if (getActivity() != null) {
                FragmentB fragmentB = new FragmentB();
                ((MainActivity) getActivity()).replaceFragment(R.id.frame, fragmentB);
            }
        });
    }
}

这时 LeakCanary 会提示发生了内存泄露 :

├─ androidx.appcompat.widget.AppCompatButton
    │    Leaking: YES (View detached and has parent)
    │    mContext instance of com.james.myapplication.MainActivity with mDestroyed = false
    │    View#mParent is set
    │    View#mAttachInfo is null (view detached)
    │    View.mWindowAttachCount = 1
    │    ↓ AppCompatButton.mParent
    ╰→ androidx.constraintlayout.widget.ConstraintLayout
    ​     Leaking: YES (AppCompatButton↑ is leaking and ObjectWatcher was watching this)
    ​     mContext instance of com.james.myapplication.MainActivity with mDestroyed = false
    ​     View#mParent is null
    ​     View#mAttachInfo is null (view detached)
    ​     View.mWindowAttachCount = 1
    ​     key = b1205e98-e894-4cd1-a702-ef2f06a55ab9
    ​     watchDurationMillis = 6853
    ​     retainedDurationMillis = 1848
    ​     key = ca1cfff1-c424-4273-b6fb-90f9e3d44c96

通过 view detahced and has parent提示, FragmentA 中的 mButton 引起了泄露.

分析

image

参考官方的生命周期图, Fragment 的生命周期

  • 直接Replace : onDestroyView() -- onDestroy() -- onDetach()
  • Replace 并且 addToBackStack : onDestroyView()

后者的 Fragment 只是视图被销毁了, 实例没有被销毁, 在使用回退栈回退后, 会重新通过 onCreateView 创建一个新的视图.

这就意味着, 在 onDestroyView() 之后, 当前的视图View已经没有任何价值, 在源码里也做了处理 f.mView = null

                        f.mContainer = null;
                        f.mView = null;
                        // Set here to ensure that Observers are called after
                        // the Fragment's view is set to null
                        f.mViewLifecycleOwner = null;
                        f.mViewLifecycleOwnerLiveData.setValue(null);
                        f.mInnerView = null;
                        f.mInLayout = false;

然而此时 Fragment 实例 f 是没有被销毁的, 我们自己 findViewById 查找的 View 是可以作为成员变量保存的.

打开AS的profiler, dump内存后, 证实了 mButton 不为null, 并且通过 mParent 持有了父布局的引用. (Fragment$1是 mButton 持有的clickListener内部类.)

image

显然, 此时的 mButton 应当被回收, 因为下次进入页面还会通过 onCreateView() 查找一个新的 mButton. 我们手动把引用置为null.

FragmentA.java   
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mButton = null; //置为null
    }

再次进行以下操作 :

  1. replace FragmentA()
  2. replace FragmentB() 并加入回退栈

此时leakCanary无泄漏提示. dump内存, mButton = null , 并且此时 mButton 持有的内部类 clickListener 也被回收了.

1576596486_1_.jpg

有人会说, Fragment 对象并没有销毁, 即使在 onDestroyView() 之后 view 依然占用内存, 在 onDestroy() 时依然能被正确回收. 但是 onDestroyView 到 onDestroy 这段时间内, view 的存在会使得onDestroyView()行为失效.

因为在下次 onCreateView 时, view又会被分配新的内存. 当前的 View 的生命周期已经结束了, 应当被立即回收掉.

另一种常见的情况是 ViewPager 使用 FragmentPagerAdapter 时.

FragmentPagerAdapter

使用 FragmentPagerAdapter 时超过缓存 pageLimit 的 Fragment 会进行 FragmentTransaction.detach()。此时 Fragment 的实例同样没有被销毁. 当页面数量很多时, 即使超出 pageLimit 的 Fragment 中, view 也会占用大量的内存.

public class ViewPagerTest extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewpager);

        ViewPager viewPager = findViewById(R.id.viewpager);

        List<Fragment> fragments = new ArrayList<>();
        fragments.add(FragmentA.newInstance(0));
        fragments.add(FragmentA.newInstance(1));
        fragments.add(FragmentA.newInstance(2));
        fragments.add(FragmentA.newInstance(3));
        fragments.add(FragmentA.newInstance(4));

        //在使用FragmentPagerAdapter的情况下, 超出 pageLimit 的Fragment只会走onDestroyView(), 也就是实例仍然存在于内存中
        //此时Fragment如果有View的强引用, 仍然会继续占有内存
        viewPager.setOffscreenPageLimit(1);
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }
        });
    }
}

同样, 我们在 onDestroyView() 中把使用到的 View 手动置为 null , 这在图片较多的 ViewPager 中尤其明显, 能节约大量内存.

框架中的处理

1. SDK中ListFragment中的处理

SDK 中的 ListFragment 中, 也在 OnDestroyView 时手动把使用到的View置空.

ListAdapter mAdapter;
ListView mList;
View mEmptyView;
TextView mStandardEmptyView;
View mProgressContainer;
View mListContainer;
CharSequence mEmptyText;
boolean mListShown;

/**
 * Detach from list view.
 */
@Override
public void onDestroyView() {
    mHandler.removeCallbacks(mRequestFocus);
    mList = null;
    mListShown = false;
    mEmptyView = mProgressContainer = mListContainer = null;
    mStandardEmptyView = null;
    super.onDestroyView();
}

2. ButterKnife中的处理

ButterKnife 提供了一个 unBind() 方法, 供我们在 Fragment#onDestroyView() 时调用.

查看apt生成的 XX_ViewBinding 文件的 unBind() 方法

public class FragmentA_ViewBinding implements Unbinder {
  private FragmentA target;

  @UiThread
  public FragmentA_ViewBinding(FragmentA target, View source) {
    this.target = target;

    target.editText = Utils.findRequiredViewAsType(source, R.id.et, "field 'editText'", EditText.class);
  }

  @Override
  @CallSuper
  public void unbind() {
    FragmentA target = this.target;
    if (target == null) throw new IllegalStateException("Bindings already cleared.");
    this.target = null;

    target.editText = null;
  }
}

作者的说明

You only need to call unbind() in fragments in onDestroyView because it can cause a leak if the fragment is re-used. For activities you do not need to call the method because the references form a cycle which will be correctly GC'd.

3. Kotlin Android Extention中的处理

同样, 在 onDestroyView() 的时候清空保存 view 的容器.

// $FF: synthetic method
public void onDestroyView() {
   super.onDestroyView();
   this._$_clearFindViewByIdCache();
}

总结:

通常的内存泄露都是对象由于被强引用指向导致不能回收, 在安卓中最多的就是 Activity, Fragment 关闭时出现的泄露. 移动开发中内存比较吃紧, 频繁使用的对象要做持久化缓存, 超出生命周期的对象应当及时回收.
在上面的场景中, Fragment 并没有销毁, 只是因为 view 超出了他应当存在的生命周期(因为在onCreateView中会被重新分配), 在 onDestroyView() 后他仍然存在, LeakCanry 也把这种判定为内存泄露.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容