Handler is responsible for message sending and processing, sends the message eventually calls to a handler. The enquemessage (), then calls to messagequeue. Enquemessage (), method, send a message to the messagequeue maintenance list, And assigns the sender handler to message.target.

Message stands for message. It stands for events. Message is the carrier of events. A large number of Message objects are created and recycled in an app, so the global pool of Message is encapsulated in a single linked list data structure in the Message class, which is obtained by message.obtain (). If a message cannot be obtained, a new message is created. Call recycle() to reclaim unused Message objects. It facilitates message reuse and saves resources and memory.

Messagequeue maintains a messagequeue and a single linked list data structure, which is beneficial to save resources and memory. The physical storage memory of its elements does not need to be continuous and relies on Pointers to connect to the next node.

Which is message-driven, invokes the messagequeue. Next () continuously polling messagequeue of messages, delete the message and call. If there are news was taken as target. Dispatchemessage (), a callback message processing result, If there is no message, it blocks in the next () method.

The message mechanism implements communication between threads. A thread can only have one Looper, one messagequeue, and multiple handlers. Loop.preparelooper(), creates a Looper object and creates a Messagequeue object along with the looper.

The main thread has already created a looper in activityThread’s main method and called loop() to start the loop, so the main thread can create handler instances and send handler messages without error. Child threads that want to use handler must first call prepare () to create looper and Loop () to start polling.

A memory leak is essentially a long – life object that references a short – life object, causing the short – life object to complete its task and not be collected by the garbage collection mechanism. When we use handler, whether we write it as an inner class or an anonymous inner class, we’re going to hold external classes like activity objects, Message holds handler objects, Messagequeue holds Message objects, Looper holds Messagequeue, Looper is thread-bound. Activity — > Handler — > Message — > Messagequeue — > Looper — > current thread; The activity is held by the current thread and cannot be reclaimed, causing a memory leak.

Solve the memory leak: defines handler into a static inner class, internal holds the activity of weak references, in the activity. The destroy () call handler. Removecallbackandmessage (null).