Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - can mainThread handlers cause memory leaks?

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 enter image description here

like image 718
j2emanue Avatar asked Jan 05 '17 05:01

j2emanue


People also ask

What causes memory leaks in Android?

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.

What is the main cause of memory leaks?

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.

How do you identify memory leakage in an Android application?

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.


1 Answers

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.

like image 50
Hasif Seyd Avatar answered Oct 16 '22 14:10

Hasif Seyd