Save memory with Android Fragment
January 01, 2019 -This is not actually written on 2019. I just wish I did write this sooner.
I had an Android project where the navigation stack could hold a lot of Activitys. A user might open a post from
another post infinitely. I observed some OutOfMemory errors because the market was dominated by low-end devices.
The idea that reduced the memory footprint at that time was to let GC collects unused View if the View is not
visible. Let's say we have PostActivity with PostA. When that PostActivity is overlaid by another PostActivity,
the View is taking memory even when it's not visible.
What we did was to extract the logic into a PostFragment. In the PostActivity we modify the code. Below code is just
from my hazy memory. It may need more tweaks to work now.
fun onStart() {
super.onStart()
getFragmentManager().beginTransaction()
.attach(fragment)
.commit()
}
fun onStop() {
getFragmentManager().beginTransaction()
.detach(fragment)
.commitAllowingStateLoss()
super.onStop()
}
Afterwards, PostFragment will have its onDestroyView() called when PostActivity is overlaid by another Activity.
The hard part was to cleanly separate which logic PostFragment depended on the View and which did not. We used
MVP pattern so only the V needed to be separated: PostFragmentPresenterListener and
PostFragmentWithViewPresenterListener. Pardon the long names.
As always, it was not a silver bullet. It traded-off memory with computation time to inflate the View in
Activity.onStart.