Avoid Memory Leak Recommendations For Android Application

Amar Kumar
2 min readSep 16, 2021

--

Avoid Memory Leak Recommendations

1- Try to avoid declaring a viewmodel in activity Because if we use the same viewmodel in a fragment , Viewmodel stays in memory until Activity kills after destroying the fragment.

2- Try to avoid holding the reference of Activity or Fragment.

  • If needed then make the reference as null in onDestroy() of Activity or Fragment;
  • If we are registering a Listener then we should unregister a particular listener.
  • If we are assigning any class as global then we should either use in method scope or make it clear as activity or fragment destroyed.
  • Never use static variables for views or activities or contexts.

3- SingleTon Class

  • Try to avoid activity or fragment context for a singleTon class. If we need context we should pass applicationContext().
  • If you really have to use activity or fragment context, then when the activity is destroyed. We should ensure that the context we passed to the singleton class is set to null.

4- we should try to never create a static variable of an inner class.

5- AsyncTask

  • We should always cancel the asyncTask when activity is destroyed. This is because the asyncTask will still be executing even if the activity is destroyed.

6- Thread

  • Close thread in activity or fragment onDestroy() to avoid thread leak.
  • If we are using the Handler with postDelay(), before doing any action on view we should first check if the activity or fragment is alive or not.

7- if we used ButterKnife() to bind views. So we should always unbind views on onDestroy().

How to detect Leak:- I used Android Profiler to Detect Memory Leak:-

https://betterprogramming.pub/improve-apps-performance-with-android-profilers-edb240deeb71

https://developer.android.com/studio/profile/memory-profiler

Amar kumar

SSE(Appinventiv)

--

--