This project is all about shows common patterns of memory leaks in Android development and how to fix them
- Do not keep long-lived references to a context-activity
public static Context mContext;
public NoLifeCycleClass(Activity myActivity) {
mContext = (Context) myActivity;
}
- Try using the context-application instead of a context-activity
StringUtilsUI.doSomeLongRunningTask(getApplicationContext());
- Avoid non-static inner classes
public class DialogCountdown extends BaseDialogFragment {
private class CountDownHandler extends Handler {
//do some work
}
}
- 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();
}
}
}
- 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;
}
}
- Avoid Auto-Boxing
public Integer exampleAutoBoxing(){
int a = 5;
Integer result = a * a;
return result;
}
public Integer hiddenAutoBoxing(){
return 5;
}
- 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);
}
- LeakCanary from Square is a good tool for detecting memory leaks in your app