Android Messaging mechanism

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.