简体   繁体   中英

A reference to a retained fragment in a UI fragment. How can the UI fragment be deleted from memory after I rotate the screen?

I'm reading the FragmentRetainInstance sample. There is the variable RetainedFragment mWorkFragment in UiFragment . So how can a UiFragment be deleted from memory after I rotate the screen? As far as I understand, mWorkFragment is a reference to something that survives across screen rotations and other configuration changes.

Update #1

I rotated the screen and pressed Initiate GC, and then pressed Dump heap. I saw the number of UiFragment instances was 1. Why? I expected to see 2: 1 for the current orientation and 1 for the previous orientation.

Initiate GC:

在此处输入图片说明

Heap dump:

在此处输入图片说明

As I said in my comment, the UiFragment from the sample you linked to isn't leaked. It does indeed hold a reference to the RetainedFragment which survives the configuration change but that reference doesn't matter. The GC will start from a GC root and from there it traverses the objects following the references it finds inside the objects. As the UiFragment isn't referenced from something that lives(like the RetainedFragment) it will be outside of the hierarchy of live objects and will be eligible for garbage collection.

If you want to see a memory leak, in the sample you linked to, remove the line mProgressBar = null; from the in onDetach() callback of the RetainedFragment. With this change the RetainedFragment will hold a reference to the UiFragment(actually is the old activity along with all of its data) making the old Context instance to stay alive, at least until the onActivityCreated() callback of the RetainedFragment is called(inside onActivityCreated() mProgressBar will be cleared and made to point to the restored UiFragment's ProgressBar).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM