2

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.

Shrikant Ballal
  • 7,067
  • 7
  • 41
  • 61

2 Answers2

2

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

Tal Kanel
  • 10,475
  • 10
  • 60
  • 98
  • @Shrikant: if you'd like - I can offer you much better solution to clear background activities – Tal Kanel Jun 01 '12 at 06:45
  • http://stackoverflow.com/questions/10736594/what-is-the-right-way-to-clear-background-activity-activites-from-stack read this, and the the link someone posted on his answer to my question – Tal Kanel Jun 01 '12 at 06:46
  • the solution is to send broadcast which all activities registered to will finish theriself when receive – Tal Kanel Jun 01 '12 at 06:50
0

Try rotating the device a couple of times and see what happens- you'll eventually run out of memory because you're still holding a reference to previous contexts which the GC can't clear.

Dhruv Gairola
  • 9,102
  • 5
  • 39
  • 43