Android memory leaks
2014-08-01Articles:
-
Avoiding memory leaks. This great article describes base causes of memory leaks on Android. I quote summary from there:
- Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
- Try using the context-application instead of a context-activity
- Avoid non-static inner classes in an activity if you don’t control their life cycle, use a static inner class and make a weak reference to the activity inside. The solution to this issue is to use a static inner class with a WeakReference to the outer class, as done in ViewRoot and its W inner class for instance
- A garbage collector is not an insurance against memory leaks
-
How to Leak a Context: Handlers & Inner Classes. Be cautious when using inner classes inside activity. The summary:
- In Java, non-static inner and anonymous classes hold an implicit reference to their outer class. Static inner classes, on the other hand, do not.
- Avoid using non-static inner classes in an activity if instances of the inner class outlive the activity’s lifecycle.
- Instead, prefer static inner classes and hold a weak reference to the activity inside.
-
Отслеживание утечек памяти в Android приложениях. This article gives example of class for tracking memory leaks based on WeakReference.
StackOverflow discussions mostly:
- TextView with id and textIsSelectable=“true” causes leaking of the Activity object. And corresponding Stack Overflow topic. I’ve bumped into this issue personally and spent a quite some time too. Rotating emulator and heapdumping mostly :) The point is that TextView with id and android:textIsSelectable=“true” causes memory leak on Android 4.0.x, 4.1.x, 4.2.x, 4.3.x. Can’t check it on 4.4.2 because of emulator bug.
- Android EditText Memory Leak, Why does EditText retain its Activity’s Context in Ice Cream Sandwich, EditText causing memory leak. The main theme of this topics is that EditText leaks when spellchecker suggestions are used. You can turn it off but it can help or maybe not. EditText is leaking on Android 4.0.x, 4.1.x, 4.2.x. Thanks god, seems like it’s fixed in Android 4.3, API 18 (checked on Nexus 7 2013 emulator). Although corresponding issue is still open.
- Fragments are not being released from memory. A valuable advice - use weak references to point to any object that references its context outside of your Activity. I’m not sure is it a proper approach to weak referencing ViewPager, but for some more “distant” object like AsyncTask it might be reasonable.
Videos:
- Google I/O 2011: Memory management for Android Apps . Presentation by Patrick Dubroy.