Android - can mainThread handlers cause memory leaks?

I'm curious why there is a memory leak below because mHandler is created on mainThread, and now that onDestroy is called wont, it just kills the thread? how can a handler exist after the destruction of activity? I did not create a new thread. Do I understand that a handler, if it has things, will remain in the message queue even after the stream is destroyed?

Reference reading doc im here enter image description here

+6
source share
2 answers

The handler is mainly used to send events to the Message MessageQueue. Each Handler instance is associated with one thread and this thread's message queue.

so when you send runnable with a delay and exit the action, MainThread will not be destroyed, since there are still events in MessageQueue that will be processed after the delay, so this can cause memoryLeak , since your anonymous inner class runnable contains an activity link instance .

therefore, do not forget to delete all messages in onStop () from Activity by calling

handler.removeCallbacksAndMessages(null); 

this will clear all pending messages and callbacks before leaving your activity.

+13
source

They can, but not from the Runnable handler that was sent. The way Handler works is that it is associated with a stream. There must be a Looper in this thread. Looper has a message queue. When you postDelayed, you add Runnable to the Looper message queue. Thus, the thread itself has a link to Runnable. To runnable leaked, and if a non-static parent class will be leaked.

0
source

Source: https://habr.com/ru/post/1013770/


All Articles