avoid-memory-leak-android

General

Category
Battlefield
Tag
Architecture
License
N/A
Registered
Apr 9, 2018
Favorites
2
Link
https://github.com/AliAsadi/avoid-memory-leak-android
See also
GreenDroid
EffectiveAndroidUI
Visum
EliteMvp
ArmsComponent

Additional

Language
Java
Version
N/A
Created
Feb 15, 2018
Updated
Apr 2, 2019
Owner
Ali Asadi (AliAsadi)
Contributor
Ali Asadi (AliAsadi)
1
Activity
Badge
Generate
Download
Source code
APK file

Advertisement

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 ?

Screenshot

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 using WeakReference.
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()/onStop().
@Override
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