Skip to content

🔥 Examples of memory leaks and common patterns that cause them in Android development and how to fix/avoid them

Notifications You must be signed in to change notification settings

CanaanWong/avoid-memory-leak-android

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

avoid-memory-leak-android

This project is all about shows common patterns of memory leaks in Android development and how to fix them

Android Arsenal

How we can cause a leak when we use ?

How To Avoid Memory Leak?

  1. Do not keep long-lived references to a context-activity
public static Context mContext;
	public NoLifeCycleClass(Activity myActivity) {
	mContext = (Context) myActivity;
}
  1. Try using the context-application instead of a context-activity
StringUtilsUI.doSomeLongRunningTask(getApplicationContext());
  1. Avoid non-static inner classes
public class DialogCountdown extends BaseDialogFragment {

private class CountDownHandler extends Handler {
	//do some work
  }
}
  1. Avoid non-static inner classes
private static class CountDownHandler extends Handler {
	private final WeakReference<DialogCountdown> mDialogCountdownWeakReference;
	public CountDownHandler(DialogCountdown dialogCountdown) {
	super();
	mDialogCountdownWeakReference = new WeakReference<>(dialogCountdown);
	}
	public void handleMessage(Message msg) {
	if(mDialogCountdownWeakReference.get()!=null) {
	mDialogCountdownWeakReference.get().onCountDown();
     }
   }
}
  1. Clean/Stop all your handlers, animation listeners onDestroy();\
protected void onStop() {
	super.onStop();
	mHandler.clearAllMessages();
	unregisterReceivers();
	heatMapsDone();
	if (mServiceBound) {
	mServiceBound = false;
	Services.unbindFromRidesService(this, this);
	}
	if (mMapStateMachine != null) {
	mMapStateMachine.stop();
	mMapStateMachine = null;
	}
}
  1. Avoid Auto-Boxing
public Integer exampleAutoBoxing(){
	int a = 5;
	Integer result = a * a;
	return result;
}
public Integer hiddenAutoBoxing(){
	return 5;
}
  1. Avoid Auto-Boxing in HashMap
public Integer hiddenAutoBoxing(){
	HashMap<Integer, String> hashMap = new HashMap<>();
	hashMap.put(5,"Hi Android Academy");
}
public Integer noKeyAutoBoxing(){
	SparseArray<String> sparseArray = new SparseArray<>();
	sparseArray.put(5,"Hi Android Academy");
}

public Integer noValueAutoBoxing(){
	SparseIntArray sparseArray = new SparseIntArray();
	sparseArray.put(5,1000);
}

Tools which can help you identify leaks

  • LeakCanary from Square is a good tool for detecting memory leaks in your app

About

🔥 Examples of memory leaks and common patterns that cause them in Android development and how to fix/avoid them

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Java 100.0%