Archive for August, 2010

Android memory leaks

Since I’ve been banging my head against this for the last 12 hours, I thought I’d post a solution here, so other people might stumble across it and benefit.

I ran into two memory leaks in Android itself in WebView, and Typeface. Both are because of bugs in the OS, so if you’re encountering memory leaks, and all your code looks pretty watertight, (Meaning you never pass Activities as a Context to a View, and you use WeakReferences for static inner classes) you might be hitting one of these.

The first bug for WebView is described here.

The solution is just to call destroy() on your webview in the onDestroy() method of the containing activity, then set any references to that WebView to null, just in case. The app I’m working on is webview heavy, so this was causing some grief.

The second bug for Typeface is described here.

The issue was that I was creating a new Typeface from assets in the onCreate method of my activity. Every time I did this, it was allocating around 700k of memory, which then never got released. Big, big problems. The solution in this case is to initialize the typeface object in a static class (You can subclass Application and stick it there if you want, but be aware that you can’t call getAssets() before the first activity gets it’s onCreate method called.) and then use that one instance for any TextViews you may have.

The only way I managed to figure out what was causing the leaks was to go into adb shell, and then use dumpsys meminfo. That showed me a whole lot of bad.

Comments off

Related Links

Resource Links