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 ofcontext
- 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
Set View Text Align at Center in Spinner in Android
Way to Protect from Lucky Patcher/Play Licensing
How to Disable "Next" Button on a Edittext Software Keyboard (Replace with "Done" Button)
How to Setup Multiple Alarms in Android
To Run Dex in Process, The Gradle Daemon Needs a Larger Heap. It Currently Has Approximately 910 Mb
How to Add The Icon for Swipeable Tabs
How to Add a View Programmatically to Relativelayout
How to Set a Fragment Tag by Code
Zipalign - Command Not Found - MAC Terminal
Using Google Places API in Android
Android - How to Set Background Color of All Screens
Starting Activity Through Notification: Avoiding Duplicate Activities
Android - Setting Layoutparams Programmatically
Fragment in Viewpager Not Restored After Popbackstack
Coordinatorlayout Using The Viewpager's Recyclerview
Adb Doesn't Recognize My Galaxy Nexus - Win7
How to Look-Up a Contact's Name from Their Phone Number on Android
How to Avoid Restarting Activity When Orientation Changes on Android