Writing great, high-quality software is hard work. No matter how well we know a platform or how long we spend on code, there are bound to be bugs. Memory leaks are among the most common problems, and they can be particularly disruptive on mobile devices. Square set out to make memory leaks easier to track down and fix with a new library called LeakCanary. It makes leak detection almost automatic and presents results in both logcat and an easy-to-read interface.

screenshot

LeakCanary is designed to be as easy to use as possible. For most applications, it should only require a few additional lines in the app's build.gradle file, and one more line of code in your Application class. This is enough to enable automatic tracking for memory leaks in activities. For more comprehensive coverage, the RefWatcher object can be directed to observe objects that should be garbage collected.

In the event that an object isn't released properly, LeakCanary publishes a leak trace to logcat and creates a notification in the status bar. Tapping on the notification opens up a screen with a simple illustration of the leak trace that shows which class object is still holding a reference. If memory leaks are identified that can't be fixed, including known issues in the Android SDK itself, LeakCanary can be configured to ignore these without producing any notifications.

Results are temporarily saved in your app's private storage, but they can be exported through a share intent, or they can be uploaded to a server with a little bit of extra code.

LeakCanary joins Square's substantial list of open source projects. It's completely free and the user base is already exploding in size. For a little bit of backstory about how the project began, check out Square's blog post, or jump straight to the setup instructions to get started with it in your own projects.