Android - Memory leak when dynamically building UI with image resource backgrounds

前端 未结 2 548
面向向阳花
面向向阳花 2021-02-04 15:39

I have an Activity that I swear is leaking memory. The app I\'m working on does a lot with images, so I\'ve had to be pretty stingy with memory when working directly with Bitma

相关标签:
2条回答
  • 2021-02-04 16:03

    Rich,

    If you are going to be dealing with that many Bitmaps you should aggressively clean them up when they are not needed (onPause is a good start).

    I remember a discussion from a long time ago about ImageViews and their odd behavior with lingering references to their displayed bitmaps. From what I do recall is that you should remove all references to the current context from the ImageView if you are going to keep the layout alive but don't want to leak. Remove the onClick listener and bitmap. Call .recycle() on the Bitmap if you want to aggressively free memory. Make sure you don't have any static fields with lingering references to the context or inner class references to it.

    The code for Android's launcher was also mentioned during this as a good reference where they do some of these things. OpenSource is your friend.

    EDIT

    Found Romain Guys article. Basicly he mentions this part of the way though

    This example is one of the simplest cases of leaking the Context and you can see how we worked around it in the Home screen’s source code (look for the unbindDrawables() method) by setting the stored drawables’ callbacks to null when the activity is destroyed.

    Now I've never had to manage this type of memory usage (yet) so from here I suggest looking at The Home Screen Source for more details. You'll find their unbind() method on line 620

    0 讨论(0)
  • 2021-02-04 16:10

    This is going to sound a little odd, but I have had trouble with apps that did any bitmap manipulation on a thread other than the one associated with the Handler for your Activity. In particular, I had an app that was leaking a lot of memory by doing image manipulation in a java.util.Timer thread. When I migrated that code over to using Handler.postDelayed, the memory issues cleared themselves up.

    0 讨论(0)
提交回复
热议问题