In accordance with the principles of Android handler detailed analysis we can know that when creating handle objects in the main thread, the main thread creates a loop object by default using the Threalocal function to bind the loop object and the main thread.
Can we create a loop object and child thread bindings in a child thread that's actually possible?
In this way we create a Looper object in the child thread, bind the Looper object and the child thread, execute the Loop.loop () function in the child thread inside is to turn on a dead loop to traverse the message in the message queue, so the child thread never quits.
When we call in the main thread to get the Subhandler object, we can send a message to the child thread.
A toast is popped in handlmessage after a child thread receives a message
Why is it possible to eject a toast in a child thread, because there is a Looper object and the child thread binding in the child thread. A toast is normally only popped in the main thread, because the main thread has a default Looper object and the main thread binding. Now that we have created a Looper object in the child thread, we are able to pop a toast on the child thread
Summarize:
If a thread is to process a message, it must have its own looper, and it is clear that we are going to call Looper.prepare () in a child thread to turn on a message loop for a thread, and by default the new thread in Android does not have the message loop turned on. (except for the main thread, the main thread system automatically creates a Looper object for it, opening the message loop.) The Looper object holds messages and events through MessageQueue. A thread can have only one looper, corresponding to a MessageQueue. Then let Looper start working through Looper.loop (), fetching messages from the message queue and processing the messages.
There is a memory leak in the code above, because the Loop.loop () method inside the thread is opening a dead loop to iterate over the message queue, so even if the activity exits, it will not quit, and the thread has a mainactivity reference to the toast. Will cause the activity to exit, but the reference in the activity thread still exists, causing a memory leak
How to solve, we should quit in the activity of the ondestory, stop the dead loop variable message queue, you can call the Looper object's quit function, so first we need to get the Looper object
Second, call the QUIT function in the activity's ondestory
is not quite the classic
Android handle detailed 2 main thread send message to child thread