To clear all background activities I did the following:
I kept a static array list, and whenever I used to go from one activity to another, in the onCreate() method of new activity, I added the object of current activity into that list like this:
SomeClass.addActivity(CurrentActivity.this);
I added the above statement in each activity.
The addActivity():
public void addActivity(final Activity activity) {
activityList.add(activity);
}
And when I wanted to clear the stack, I called:
public boolean clearStack() {
for (Activity activity : activityList) {
activity.finish();
}
activityList.clear();
return (activityList.isEmpty());
}
In this way, I cleared my activity stack.
But it produced a memory leak. It’s not the right way to do that. It’s not ok to hold references to activities. Can you guys explain me why and how exactly memory leak occurred in this case?
I used MAT for eclipse to find this memory leak in my app.
Any help would greatly be appreciated.
Holding references to activities outside their context (when they are in background or “closed”/finished) causes memory to leak – the Android operating system would like to clear from memory “old” activities when it decides it’s the time to do so (You can’t control it manually).
In that case – the garbage collector would try to free the activity / activities from memory, but because something (your array of references to activities) is holding a reference to it – it can’t be garbage collected, so it can’t free it from memory- and that’s a sample of a memory leak.
This document describes how to avoid memory leaks:
http://android-developers.blogspot.co.uk/2009/01/avoiding-memory-leaks.html