avoid-memory-leak-android

Additional

Language
Java
Version
N/A
Created
Feb 14, 2018
Updated
Apr 9, 2018
Owner
Ali Esa Assadi (AliEsaAssadi)
Contributor
Ali Esa Assadi (AliEsaAssadi)
1
Activity
Badge
Generate
Download
Source code
APK file

Advertising

avoid-memory-leak-android

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

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