How to Fix Memory Leaks in Your Android App

Memory leaks may be the cause of your app's poor performance on certain devices or the occasional failure of Android Studio's Instant Run features.‍ 

When Does A Memory Leak Happen?

Java has a great feature called the garbage collector (GC). The garbage collector periodically scans and deletes objects that the app does not need.  A memory leak will happen when there are objects that there are not in use by the app but the garbage collector cannot recognize them. Hence, sometimes the garbage collector fails to identify some unused objects. These objects stay in memory and waste space, making the app run slower or crash.‍

How To Detect Memory Leaks?‍

There are several ways to do so. We are going to cover some of them in this article.

But first, let’s write some code that could produce a memory leak. We will create an app with two activities. Activity A will have a button that opens Activity B. Alongside this, we will also create a singleton class that holds a static reference of a Context.

class Manager { 
	private static Manager ourInstance;
	private Context context;
	static Manager getInstance(Context context) {
		if (ourInstance == null) {
			ourInstance = new Manager(context);
		}
	return ourInstance;
	}
	private Manager(Context context) {
		this.context = context;
	}
}

We are going to call this singleton from Activity A

Manager.getInstance(this);

Detecting Memory Leaks Using Android Studio’s Monitors

android memory leaks

Android Studio provides handy tools for profiling the performance of your app, and one of them is the Memory Monitor. We can use the Memory Monitor to detect memory leaks through the following steps:

  1. Run your app on your mobile device or an emulator.
  2. Open Android Monitor (Press Cmd + 6 in Mac or Alt + 6 in Windows). At the top of Memory Monitor, click on Start Allocation Tracking.
  3. Use the app around the part that you suspect may be experiencing a memory leak. In our example, we will go to another activity.
  4. Click on Initiate GC to force the garbage collector to start collecting objects that are not currently in use and remove them. You should see the memory graph decline a little bit.
  5. Click on Dump Java Heap to let Android Studio generate a .hprof file that contains a heap snapshot. The easiest way to check a memory leak is by using Analyzer Tasks
  6. Open the Analyzer Tasks tab and then click on Run at the top of this tab. You should see the leaked activities in the Analysis Results tab below the Analyzer Tasks tab.

Detecting Memory Leaks Using Leak Canary

‍Leak Canary is a library made by Square and it's a very fast way to detect memory leaks. Leak Canary allows you to detect memory leaks in longer runs because you don’t need to connect your device to the Android Studio and monitor your app for a long period of time. Leak Canary will send you notifications whenever there is a memory leak.

Integration of Leak Canary is really easy. All you need to do is to add the following to your app level build.gradle file:

dependencies {
	debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'
	releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
	testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
}

Then add the following code to your Application class:

@Override public void onCreate() {
	super.onCreate();
	if (LeakCanary.isInAnalyzerProcess(this)) {
		// This process is dedicated to LeakCanary for heap analysis.
		// You should not init your app in this process.
		return;
	}
	LeakCanary.install(this);
	// Normal app init code... 
}

And that’s it, you’re good to go.

Detecting Possible Leaks With Infer

‍Infer is a static analyzer tool made by Facebook that helps you find possible null pointer exceptions and resource leaks as well as annotation reachability, missing lock guards, and concurrency race conditions. It’s a good tool to add to your CI to overcome all possible bugs. It's also open source, so development of the tool is still evolving. You can find more info about Infer in their Quick Start documentation.

No comments:

Post a Comment