2

I'm currently working on an android app with several activities. Most of the time, the app works fine, but from time to time an Out of Memory Exception occurs. (usually when trying to load the large background image for the next activity)

I couldn't find any obvious memory leaks, so I created a heap dump when the exception occurred (like described here) and tried to analyse it with MAT. I haven't done something like this before, so I wasn't sure what exactly I should be looking for. I started clicking through the larger byte objects and the second one seems to be a Bitmap belonging to an ImageButton:

enter image description here

The Path to GC roots shows me an com.android.internal.policy.impl.PhoneWindow instance:

enter image description here

The thing is, the only ImageButton in my whole application is in my launch activity and between that launch activity and the crashing activity are at least 2 more activities.

So why is this image still in the heap?? The ImageButton is simply defined in the layout xml file using the android:src attribute, nothing is done via Code there. There are also a lot of other smaller objects from earlier activities in the heap.

I also wrote a little HelloWorld application and took a look in the heap dump of it and it seems, that android keeps the objects of previous activities in the heap. If this is the case, then an Out of Memory Exception has to be thrown some day, so I guess something must be wrong on my analysis :/

trincot
  • 317,000
  • 35
  • 244
  • 286
FahneImWind
  • 146
  • 6

2 Answers2

0

You might want to look at Bitmap managing in the developer's documentation.

In particular: a bitmap is kept in memory as long as a reference exists to it. So, if you absolutely have to use large bitmaps for your buttons (as you are describing) you might be do better by loading it manually and using recycle as soon as your Activity disappears from sight.

DigCamara
  • 5,540
  • 4
  • 36
  • 47
  • 1
    I'm recycling the large images now and calling finish() for no longer needed activities - no OOM Exception seen anymore :) – FahneImWind Mar 02 '13 at 21:26
0

Okay, I just found this and realized, that stopped activities (and their objects) are NOT destroyed as long they are on the back stack. Even not if the active one needs more memory. With this knowledge it is obvious why these objects like that ImageButton are still in the heap.

I still have to figure out the best way to release these resources, but I guess this strongly depends on the application itself and is hard to answer in general.

Community
  • 1
  • 1
FahneImWind
  • 146
  • 6