How to Detect Memory Leak in Android Studio

Even though both Dalvik and ART optimize RAM usage with garbage collection (GC), it doesn’t mean a developer can do whatever they want without checking how an app allocates and releases RAM.

How to trigger memory leaks

Developers need to aggressively stress their app code and try forcing memory leaks. They should let the app run for several hours before checking the heap. The smaller the leak, the longer an app should be run to see it.

The following are 2 ways to trigger memory leaks:

1) Switch back and forth between portrait and landscape mode multiple times while in different activity states.
2) Switch between your app and another app while in different activity states.

Investigating RAM usage

Google provides a detailed guide about analyzing how RAM is used in an app. It can be read here.

Fortunately, there is a library called LeakCanary that can help you avoid working with heap dump.

Using LeakCanary to detect the leak

LeakCanary is a memory leak detection library for Android and Java.

Steps to use LeakCanary:

1) Add the following lines to build.gradle

dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.4-beta2'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'

2) Initialize the library

public class ExampleApplication extends Application {

@Override public void onCreate() {

private void enabledStrictMode() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() //
.detectAll() //
.penaltyLog() //
.penaltyDeath() //

3) Check for leaks in a nice display

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.