How to Find Memory Leak Class/Activity in Android

Can handler class with activity's context cause memory leak?

You have 2 sources of leaks in your code:

  • Using context outside the activity lifecycle. You can avoid this by using applicationContext instead of context
  • Additionally, the anonymous class you are using with handler.postDelayed holds a reference to the your activity. So you'll need to remove that in onDestroy like this:
    override fun onDestroy() {
super.onDestroy()
handlerWithContext.removeCallbacksAndMessages(null)
}

Lastly, use leakcanary to detect leaks in your code. Here's the getting started guide

Find memory leaks in the Activity code to free memory usage and avoid OutOfMemory Exception

Are you properly abandoning the focus listener from AudioManager?

AudioManager#abandonAudioFocus(OnAudioFocusChangeListener listener)

The actual OOM might be the result of non recycling lists as mentioned, but that could be the cause of your memory leak.

Memory leak in the empty Activity

Your RefWatcher should be in the onDestroy() method, not onCreate() (see a similar reported issue here).

You don't even need to do this, since LeakCanary watches Activity references automatically. From the FAQ:

LeakCanary.install() returns a pre configured RefWatcher. It also installs an ActivityRefWatcher that automatically detects if an activity is leaking after Activity.onDestroy() has been called.



Related Topics



Leave a reply



Submit