I am curious why the below is a memory leak because the mHandler is created on the mainThread and now when onDestroy is called wont it just kill the thread ? how can the handler exists after the activity is destroyed ? i have not made a new thread. Am i to understand that a handler if it has things i the message queue will remain even after a thread is destroyed ?
The reference doc im reading is here
Memory leaks occur when an application allocates memory for an object, but then fails to release the memory when the object is no longer being used. Over time, leaked memory accumulates and results in poor app performance and even crashes.
DEFINITION A memory leak is the gradual deterioration of system performance that occurs over time as the result of the fragmentation of a computer's RAM due to poorly designed or programmed applications that fail to free up memory segments when they are no longer needed.
The Memory Profiler is a component in the Android Profiler that helps you identify memory leaks and memory churn that can lead to stutter, freezes, and even app crashes. It shows a realtime graph of your app's memory use and lets you capture a heap dump, force garbage collections, and track memory allocations.
Handler's are mainly used to post events to the Thread's MessageQueue.Each Handler instance is associated with a single thread and that thread's message queue.
so when you post a runnable with a delay, and exit from the activity, the MainThread will not be destroyed, as there are still events in the MessageQueue to be processed after a delay, so this can cause a memoryLeak as your anonymous innerclass of runnable is holding the reference of activity instance .
so make sure to remove all the messages in onStop() of Activity by calling
handler.removeCallbacksAndMessages(null);
this will clear all the pending message and callbacks before leaving your activity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With