Memory not freeing after fragment is removed - android

I have a Fragment which has a RecyclerView.
In this RecyclerView, I may occasionally download and display images (loaded with Glide into ImageView.
So when I open the Fragment, used memory may sometimes jump from around 30MB to around 100MB or even more.
After the Activity that is holding the Fragment is finished, the memory does not free up. It stays the same as before.
I checked Glide documentation and apparently we don't have to worry about freeing up Bitmaps in RecyclerView. This is a huge issue, because app often crashes due to OOM because of this.
How should I correctly handle freeing up memory when Fragment is removed?
Edit: another observation
Another thing I noticed is that if I finish the Activity and then start the same Activity again. Memory will jump back down for a moment and then back up to 100MB, which leads me to believe that the memory is cleared before launching the Fragment again.

Garbage Collection is sometimes a painful issue in Android.
Most developers fail to consider this issue and just keep developing without any sense of resource allocation.
This will of course cause memory problems such as leaks, OOM and unnecessary resource binding. There is absolutely no automatic way to free up memory. You can not, under any circumstances, rely solely on the Garbage Collector
Whenever you pass the Fragment's or Activity's onDestroy() method, what you can and should do is erase any construct that shall no longer be required in the application. You can do the following :
Avoid anonymous instances of listeners. Create listeners and destroy them when you no longer need them.
Set all the listeners (be them click, longclick, etc) to null
Clear all variables, arrays. Apply the same procedure to all the classes and subclasses contained inside the Activity/Fragment
Set the variable to null whenever you perform any of the previous steps on that given class (applies to all variables)
What I ended up doing was creating an interface like
public interface clearMemory(){
void clearMemory();
}
and implementing it on every class, be it Activity, Fragment or a normal class (includes adapters, custom views, etc).
I would then call the method whenever the class was to be destroyed (because the app was being destroyed or whenever I felt need to do so. Careful not to dispose in normal runtime)
#Override
public void onDestroy(){
clearMemory();
}
public void clearMemory(){
normalButtonOnClickListener = null;
normalButton.setOnClickListener(null);
normalButton = null;
myCustomClass.clearMemory(); // apply the interface to the class and clear it inside
myCustomClass = null;
simpleVariable = null;
...
}
By implementing this in a systematic way, my applications' memory management has become easier and leaner. One can then then know/control exactly how and when the memory is disposed.

This is adding on to Ricardo's answer.
You can add the following code to initiate garbage collection in Android:
Runtime.getRuntime().gc();
Note: Call this function after you've made all local variables null. Execution of this code doesn't guarantee that the system will garbage collect on your app, it merely hints that it might be a good time to do it.
I've used this in all my activities' onDestroy(), and it always seems to work when I want it to.
Give it a try, it might help you out.

Related

How to Find Unwanted References in Android Using Android Profiler

I'm trying to get better at hunting down memory leaks in Android.
I have discovered the Android Profiler and learned how to perform a heap dump and how to determine if there are too many instances of a given object in memory.
I have read that one of the ways to get to the root of why an unwanted object is still hanging around is to highlight it and "look at what objects are still holding references to it and trace your way back to the original cause."
So... in this screenshot you can see the undesirable situation: I have three instances of MainActivity... and all three of them have a number in the "depth" column signaling they are really leaks.
If the object in question were a class of my own creation, then the process would be more straight-forward, but since we're dealing with an actual Activity here, when I highlight any one of the three, there is a massive list of objects referencing it (the list goes far beyond the screenshot).
Surely most of these are normal/benign references -- How am I supposed to tell which ones are worth investigating?
What are the clues? Is it the " this$0 " ? Or the massive number in the retained column? A depth number matching the object in question? I'm just guessing at this point.
Surely I'm not expected to go through the entire list mulling to myself, "Nope... can't be that one... that's a normal part of Android Framework X,Y, and Z..."
I'm trying to get better at hunting down memory leaks in Android.
I will give couple of examples but first, due to the number of questions you asked that is not related to your topic
I will first explain what you see in "Instance view";
Depth: The shortest number of hops from any GC root to the selected instance.
0 is for "private final class" or static members
if it's blank it's going to be reclaimed - which is harmless for you
Shallow Size: Size of this instance in Java memory
Retained Size: Size of memory that this instance dominates (as per the dominator tree).
Is it the this$0?
this$0 is a synthetic variable generated by the compiler which means "one level out of my scope", it's a parent object of a non-static inner class.
How am I supposed to tell which ones are worth investigating?
It depends, if the depth is 0 and it's your code - investigate, maybe it's a long running task with bad end condition.
When analyzing a heap dump in the Memory Profiler, you can filter profiling data that Android Studio thinks might indicate memory leaks for Activity and Fragment instances in your app.
The types of data that the filter shows include the following:
Activity instances that have been destroyed but are still being referenced.
Fragment instances that do not have a valid FragmentManager but are still being referenced.
In certain situations, such as the following, the filter might yield false positives:
A Fragment is created but has not yet been used.
A Fragment is being cached but not as part of a FragmentTransaction.
Filtering a heap dump for memory leaks.
Techniques for profiling your memory
While using the Memory Profiler, you should stress your app code and try forcing memory leaks.
One way to provoke memory leaks in your app is to let it run for a while before inspecting the heap.
Leaks might trickle up to the top of the allocations in the heap.
However, the smaller the leak, the longer you need to run the app in order to see it.
You can also trigger a memory leak in one of the following ways:
Rotate the device from portrait to landscape and back again multiple times while in different activity states. Rotating the device can often cause an app to leak an Activity, Context, or View object because the system recreates the Activity and if your app holds a reference to one of those objects somewhere else, the system can't garbage collect it.
Switch between your app and another app while in different activity states (navigate to the Home screen, then return to your app).
A growing graph is a big indicator
If you observe a trend line that only keeps going up and seldomly goes down, it could be due to a memory leak, which means some pieces of memory cannot be freed. Or there’s simply not enough memory to cope with the application. When the application has reached its memory limit and the Android OS isn’t able to allocate any more memory for the application, an OutOfMemoryError will be thrown.
Turbulence within a short period of time
Turbulence is an indicator of instability, and this applies to Android memory usage as well. When we observe this kind of pattern, usually a lot of expensive objects are created and thrown away in their short lifecycles.
The CPU is wasting a lot of cycles in performing Garbage Collection, without performing the actual work for the application. Users might experience a sluggish UI, and we should definitely optimize our memory usage in this case.
If we are talking about Java memory leaks
public class ThreadActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_task);
new DownloadTask().start();
}
private class DownloadTask extends Thread {
#Override
public void run() {
SystemClock.sleep(2000 * 10);
}
}
}
Inner classes hold an implicit reference to their enclosing class, it will generate a constructor automatically and passes the activity as a reference to it.
The above code is actually
public class ThreadActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_task);
new DownloadTask(this).start();
}
private class DownloadTask extends Thread {
Activity activity;
public DownloadTask(Activity activity) {
this.activity = activity;
}
#Override
public void run() {
SystemClock.sleep(2000 * 10);
}
}
}
In a normal case, the user opens the activity wait 20sec until the download task is done.
When the task is done the stack released all the objects.
Then the next time the garbage collector works he will release the object from the heap.
And when the user closes the activity the main method will be released from the stack and the ThreadActivity also reclaimed from the heap and everything works as needed without leaks.
In a case that the user closes/rotate the activity after 10sec.
The task is still working that means the reference for the activity still alive and we have a memory leak 💣
Note: when the download run() task is done the stack release the objects. so when the garbage collector works next time the objects will be reclaimed from the heap because there is no object referenced on it.
related Youtube playlist
And https://square.github.io/leakcanary/fundamentals/ is great.

What exactly happens when you fail to use unbind()?

I have an app where I use Butterknife, and recently I found a fragment where I had failed to call unbinder.unbind() in the fragment's onDestroyView(). I fixed the problem but it made me start thinking.
What kind of errors can this cause and why? I don't have a particular error right now but I would like to know what to watch out for in the future, and the website for the library doesn't specify the problems this could cause.
Imagine you have a retained fragment and you have initialized a view using #BindView.
An orientation change happens, which results in destroying activity instance, but not this fragment, because this fragment is a retained fragment, which means, that the field that you have initialized is still there (not null) and is holding a strong reference to the view of the previous activity, which results in leaking of the activity.
Although this might take for some small amount of time (because eventually you are going to perform another ButterKnife.bind() in onViewCreated(), right? But who knows, maybe you won't), still it is better to release resources as soon as you do not need them and let the GC do its job.
I've also thought about this question some time ago and other than this I couldn't come up to another scenario where unbind() would be strongly necessary.

Is it possible to recycle all data at OnStop() AND use a retainer Fragment?

1)It is considered a good tactic to recycle all bitmaps and data at activity's OnStop method.
2)It's also considered a good tactic to use a retainer Fragment to avoid recreating data at every configuration change.
But I don't see how these two can be combined?
Let's say I use a fragment to load a bunch of bitmaps...At OnCreate I check if that Fragment is null or not to get it's data or to instantiate a new one to create them. If i recycle all my bitmaps at OnStop() then there will be nothing left retrieve at the configuration change cause all data will have been recycled.
So....I don't see any way to combine these two tactics. Am I wrong? And if not which of the two is best to use?
My case is about loading images from SD card folder. could be only one pic, could be 500...
and showing pictues isn't all my app does so after this activity there could a need for memory by some other activity.
From Managing Bitmap Memory:
On Android 2.3.3 (API level 10) and lower, using recycle() is
recommended. If you're displaying large amounts of bitmap data in your
app, you're likely to run into OutOfMemoryError errors. The recycle()
method allows an app to reclaim memory as soon as possible.
According to this you don't even need to call recycle on devices running API 11 or higher, so it may not really be a problem for you.
You also really don't need to recycle bitmaps if the app is being destroyed as the system is going to reclaim all memory the app is taking up to begin with.
Recycle is only needed if you are showing a massive amount of bitmaps or large bitmaps and need the memory reclaimed in your app while it's still running.
Another thing to note is with the strategy you're trying, you wouldn't clean resources in the Activity's onStop() but rather the retained Fragment's onDestroy(). OnDestroy() on a retained fragment won't be called on configuration change because the Fragment isn't ever being destroyed. Thus, your resources can stay in memory beyond your Activity's lifecycle and will be destroyed at the end of your Application's lifecycle.

Should I let go of view-references etc in onStop() or onDestroy()?

Should I let go of views and other data i'm holding on to in onStop() or onDestroy()?
If I release my application's data in onDestroy() it won't be very memory-friendly towards android, am I correct? Since i'm still holding on to a couple of views after onStop(). Plus it's not guaranteed to be called and my Activity is purged from memory anyway.
If I release it in onStop(), I have to add do my setContentView() etc. in onStart() which doesn't get the Bundle that onCreate(Bundle) is handed.
Note that I have a very large application which consists of dozens of Views, most of which are custom and added by code rather than layout-files. This is largely due to the fact that I had to create a custom pager to flip through pages, since none of the built-in Views could serve my purposes (I've tried… hard…).
I have read through all the relevant Android docs but I still have no real clue on what about the view-hierarchy Android saves/recreates by itself and what I have to do myself. Or when all of that happens, meaning when Android removes the view-hierarchy from memory.
Update Question:
The android docs says this: Note: Because the system retains your Activity instance in system memory when it is stopped, it's possible that you don't need to implement the onStop() and onRestart() (or even onStart() methods at all.
If it's ok to hold on to everything, why should I care about memory-leaks when my application is being stopped like this article says? If it's destroyed and re-created, for example after a screen-rotation, I'm starting from scratch anyway?
No, you do not have to let go of anything in onStop() or onDestroy() if you only hold it in your activity (in its non-static fields). When Android let's go of your activity, the rest of your stuff is automatically thrown away (along with the activity), because there is no way to reach it from any thread (this is how Garbage Collectors work, it is not in any way special or specific to activities).
The article you refer to describes the problem where a reference to a view (or a drawable, or - broadly speaking - activity context) survives the activity that created it. Since there is a reference pointing back to the already dead activity, it becomes a zombie; what's more, it clings to all its fields, effectively zombifying them too. So if you have a view or a drawable and put it in a static field (or in any other place that might survive your activity object), then yes, you have to let it go in onStop() or onDestroy() of the relevant activity.
If Android destroys your Activity and forgoes calling onDestroy(), it means that the whole process was taken down, and this means that no memory leak can occur anyway (they are local to a single process)
Bonus answers:
views inflated from XML files take exactly as much memory as ones built in code. Why should they be heavier?
(update, after a comment) before an activity gets thrown away, Android walks its whole view hierarchy and gives each view a chance to store its state (any parcelable data) into a bundle; when recreating view Android walks the tree again and gives the data back. This is why when you recreate an activity the state of the view is saved (focus, position, content of text fields etc.). Observe how the state is only saved for elements that have an id (does not matter if they are inflated or created dynamically).

Android: removing/destroying objects when screen is rotated

I am finding that performance degrades after one or more screen rotations, and I presume that this is likely to be because an App's main Activity is destroyed and recreated each time the screen is rotated and that my app must be leaking memory when that happens.
I have read that, contrary to what one might expect, not all the objects created by an app's main Activity (or in classes called by that Activity) are destroyed when the activity is destroyed. Specifically, I think I have read (although I can't now find where) that if the View uses a large bitmap member object then the Activity's onDestroy() method should be over-ridden and the bitmap should be explicitly recycled.
Are there other objects that need to be destroyed or removed when the Activity is destroyed? What about Listeners? Is there a comprehensive tutorial or guide on this subject?
Is there a comprehensive tutorial or
guide on this subject?
Not really.
Are there other objects that need to
be destroyed or removed when the
Activity is destroyed? What about
Listeners?
Bitmaps are unusual, in part because they use memory outside of the 16MB heap, if I understand the byzantine Android memory model correctly.
Beyond large bitmaps, the biggest thing you really need to worry about are things that prevent normal garbage collection from working. Anything that holds onto the activity, directly or indirectly, from a static context will keep the activity from being garbage collected. Examples include:
static data members on classes (e.g., you rig up your own listener framework with one of your services, so your service holds onto a listener which holds onto your activity)
threads (e.g., you manually fork a background thread and do not terminate it)
Note that putting android:configChanges="orientation" in the Manifest prevents the Activity from being destroyed when the screen is rotated. So I no longer need to worry about whether I need to destroy or remove individual bitmaps or other objects! (Thanks to Ribo for pointing this out on another thread.)

Categories

Resources