Android Learning Note (13) Handler

Source: Internet
Author: User

Can be used to solve the problem that the Workerthread cannot modify the UI control as mentioned in the previous note

I. Basic principles of Handler, Looper and MessageQueue

Handler puts the message object into the MessageQueue, and Looper is responsible for constantly extracting the message object from the message queue header. The removed object is then handed to handler for processing.

Second Simple Handler Example

-Create a class that inherits Handler first, Note that importing Android.os.Handler (very important)
Class Firsthandler extends handler{}

-Replication Method Handlemessage (Message msg)

-Create Handler Object
Handler = Firsthandler ()

-Generates a message and assigns a value to the What member variable
Message msg = Handler.obtainmessage ();
Msg.what = 2;

-Place the Message object in the message queue.
Handler.sendmessage (msg);

-looper will remove the message object from the message queue;
-looper will find the handler docking corresponding to the message object (each Message object has a corresponding handler object);
-looper will invoke the Handlemessage (message msg) method of the Handler object to process the message object.

Third, the realization of the Haandler Handlemessage () method in the main thread

  Note: Messages can be sent either in Workerthread or in Mainthread, that is: handler.sendmessage (Message msg)

  1) Send a message in the run () of the new thread:

    class extends thread{        @Override        publicvoid  run () {            = "simulates data obtained from the network";             = handler.obtainmessage ();             = S;            Handler.sendmessage (msg);            }    }                    

2) the Carbon handlemessage () method. Because this method is called by the main thread, you can change the UI.

class extends handler{    @Override    publicvoid  handlemessage (Message msg) {        = ( String) Msg.obj;        Textview.settext (s);    }}

Android Learning Note (13) Handler

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.