Android applications are also message-driven. In principle, the message loop mechanism should also be provided. In fact, Google refers to the Message Loop Mechanism of Windows and implements the message Loop Mechanism in Android.
Android uses logoff and Handler to implement the message loop mechanism. Android message loops are targeted at threads (each thread can have its own message queue and message loop ).
This article introduces the principles of the Android Message Processing System in depth.
In the Android system, logoff is responsible for managing the message queues and message loops of threads. For specific implementation, see logoff source code. You can use Loop. myLooper () to obtain the Looper object of the current thread, and use Loop. getMainLooper () to obtain the Looper object of the main thread of the current process.
As mentioned above, message queues and message loops in the Android system are for specific threads. A thread can exist (or may not exist), a message queue, and a message loop ), messages of a specific thread can only be distributed to this thread. messages of a specific thread cannot communicate across threads or processes. However, the created worker thread does not have message loops or message queues by default. To enable this thread to have message queues and message loops, you must first call logoff in the thread. prepare () to create a message queue, and then call logoff. loop () enters the message loop. For example:
In this way, your thread has a message processing mechanism and processes messages in Handler.
An Activity is a UI thread that runs in the main thread. When the Android system starts the Activity, it creates a message queue and a message loop ). For detailed implementation, see the ActivityThread. java file.
Handler is used to add a message to a specific logoff message queue and distribute and process the messages in the queue. When constructing a Handler, you can specify a logoff object. If this parameter is not specified, the logoff object of the current thread is used. For detailed implementation, see logoff source code.
Multiple worker threads or other components can be created in an Activity. If these threads or components put their messages into the active thread message queue of the Activity, the message will be processed in the main thread. The main thread is generally responsible for interface update operations, and weget In the Android system is not thread-safe. Therefore, this method can effectively implement Android interface update. This method is widely used in Android systems.