Each Android app will create a thread when it starts. This thread is referred to as the main thread orUI thread. All actions of the Android app are performed by default on this thread.
But when we want to make data requests, images are downloaded. or other time-consuming operations, it is impossible toUIThread to do. Since Android after the 3.0 version number has banned this thing, throw an exception directly. So we need a sub-thread to handle the otherUIThings to do.
But this one has a problem. We are only able toUIThread processUIOperation, only time-consuming operations can be performed on child threads. Suppose we need to display a view on the Android screen after the time-consuming operation, what should we do? We are not able to flush directly on a child threadUIOf At this point we need to use the Android message mechanism. To implement communication between the main thread and the child thread. To put it simply, the sub-thread gets the data and does not directlyUIUpdate, instead of loading the data into the message sent to the main thread, there is a circular poll in the main thread that immediately receives the message from the Cheng, and then the main thread updates it after it gets the data.UI。 It's easier said than not. Let's take a detailed look at the details of how to say.
means of handling messages--handler, Looper, Messagequeuehandler
Let's start by explaining that Handler,handler, as the name implies, is the handler, and usually the way he uses itUICreate a new thread in theHandler, and overwrite hishandleMessageAnd then take the message in a time consuming threadpostTo giveUIThread. Examples include the following:
class myhandler extends Handler {@Overridepublic void Handlemessage (Messagemsg) {//Update UI}}MyHandlerMhandler =New MyHandler();New Thread() {public void run () {Mhandler.sendemptymessage (123); };}. Start ();
Here's the rule.HandlerMust be created on the main thread. As there is only theUIThread creation will makeHandlerAssociate to an existingMessageQueue。
andMessageQueueis encapsulated inLooperIn, andLooperand throughThreadLocalEncapsulated into a single thread. Last equivalent toMessageQueueassociated with a thread. So, simply put, Handler delivers the message to a thread-relatedMessageQueueIn, and thenHandlerIn fromMessageQueueThe message is removed, and it is processed.
Let's take a look at the 2 frequently used methods of handler.
void handlemessage (Message msg): Methods for handling messages
final boolean sendMessage (Message msg): Send message now
The first method we usually have in