Detailed introduction to Android handler _android

Source: Internet
Author: User

Definition of Handler
Primarily accepts data sent by child threads and uses this data to update the UI with the main thread.
Explanation: When an application starts, Android first opens a main thread (that is, the UI thread), and the main thread is the event distribution for the UI controls in the admin interface.

For example, if you click on a button, Android distributes the event to the button to respond to your action.  If you need a time-consuming operation at this time, for example: when the Internet read data, or read a large local file, you can not put these operations in the main thread, if you put in the main thread, the interface will appear suspended animation, if 5 seconds has not been completed, you will receive an Android system error prompted  "Force close". This time we need to put these time-consuming operations in a child thread, because the child thread involves UI updates, the Android main thread is not safe, that is, the update UI can only be updated in the main thread, the child thread operation is dangerous.

At this time, handler appears to solve this complex problem, because handler is running in the main line thread (UI thread), it and the child thread can pass data through the Message object, this time, handler bear the acceptance of child threads passed over ( The child thread uses the Sedmessage () method to send the Message object, which contains the data, into the main thread queue and updates the UI with the main thread.

Handler some features
Handler can distribute message objects and Runnable objects to the main thread, and each handler instance is bound to create his line thread (typically in the main thread).
It has two functions:

1. Arranging messages or runnable to be executed somewhere in a main thread
2. Arrange an action to be executed on a different thread
Some ways to distribute messages in handler

Copy Code code as follows:

Post (Runnable)
Postattime (Runnable,long)
Postdelayed (Runnable Long)
Sendemptymessage (int)
SendMessage (Message)
Sendmessageattime (Message,long)
Sendmessagedelayed (Message,long)

The above Post class method allows you to arrange a runnable object into the main thread queue.
The SendMessage class method allows you to schedule a message object with data to the queue, waiting for updates.


Handler instance
Subclasses need to inherit the handler class and override the Handlemessage (Message msg) method to accept thread data
The following is an instance of the function that modifies the contents of the button on the interface through a thread

Copy Code code as follows:

public class Myhandleractivity extends activity {
Button button;
MyHandler MyHandler;

protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (r.layout.handlertest);

Button = (button) Findviewbyid (R.id.button);
MyHandler = new MyHandler ();
When a new handler instance is created, it binds to the queue of the current thread and message and begins distributing the data
Handler has two functions, (1): Timed execution of message and Runnalbe objects
(2): Let an action, in different threads to execute.

It arranges messages, using the following methods
Post (Runnable)
Postattime (Runnable,long)
Postdelayed (Runnable,long)
Sendemptymessage (int)
SendMessage (message);
Sendmessageattime (Message,long)
Sendmessagedelayed (Message,long)

The above method begins with post to allow you to process runnable objects
SendMessage () allows you to process message objects (message can contain data)

Mythread m = new Mythread ();
New Thread (M). Start ();
}

/**
* Accept the message, process the message, this handler will run with the current main thread
* */

Class MyHandler extends Handler {
Public MyHandler () {
}

Public MyHandler (Looper L) {
Super (L);
}

       //Subclasses must override this method to accept data
        @ Override
        public void handlemessage (message msg) {
            //TODO auto-generated method stub
             log.d ("MyHandler", "handlemessage ...");
            super.handlemessage (msg);
           //Here can update UI
             Bundle B = msg.getdata ();
            String color = b.getstring ("color");
            MyHandlerActivity.this.button.append ( color);

}
}

Class Mythread implements Runnable {
public void Run () {

try {
Thread.Sleep (10000);
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

LOG.D ("Thread ... ...", "Mthread ..."); and;
msg = new Message ();
Bundle B = new Bundle ()//storing data
B.putstring ("Color", "my");
Msg.setdata (b);

MyHandlerActivity.this.myHandler.sendMessage (msg); Send a message to handler, update the UI

}
}

Related Article

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.