First, Handler
1. Use
<1> Define a Handler in the main thread, overriding the Handlemessage method
//in the main thread, define aHandler
PrivateHandlerHandler=NewHandler () {
//This method is executed in the main thread.
@Override
Public voidHandlemessage(Message msg) {
Tv_result. SetText (Msg.obj. toString ());
}
};
<2> sending messages using handler created in the main thread in child threads
Message msg=message ();
Msg.obj=content;
handler. SendMessage (msg); // Send Message
2, Handler principle
A child thread is not able to manipulate the UI thread directly, it needs to be sent to the (MessageQueue) message queue by handler, and then the Looper will continue to loop
get this message, and then get the message through the Handlemessage method execution
The role of handler is to send messages and process messages.
The role of Looper is to take messages in Message Queuing (MessageQueue)
Looper is created on the mainline Cheng.
3. The use of the Message what property
<1> set What's value
Message msg=message ();
Msg.what =requestexception;
handler. SendMessage (msg);
<2> in the Handlemessage method, perform different actions
@Override
Public voidHandlemessage(Message msg) {
Switch(Msg. What){
Caserequestsuccess://Request succeeded
Tv_result. SetText (Msg.obj. toString ());
Break ;
CaseRequestnotfind://target resource does not exist
Toast.Maketext(Mainactivity.This ,"target resource does not exist", Toast.Length_short). Show ();
Break
Caserequestexception://exception
Toast.Maketext(Mainactivity.This ,"server busy Please wait ... ", Toast.Length_short). Show ();
}
}
about Message: can be created by , in such a way, to reduce the creation of objects.
Null
Android Messaging mechanism