How to Detect Memory Leak in Android Studio

Even though both Dalvik and ART optimizes 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.

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 which can help you avoid working with heap dump.

Using LeakCanary to detect leak

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

Steps to use LeakCanary:

1) Add 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