Android Learning Note--handler Usage Summary

Source: Internet
Author: User

Transferred from: Sack Blog http://blog.sina.com.cn/s/blog_77c6324101016jp8.html

one, handler definition:
Span style= "font-family: ' Microsoft Yahei '; font-size:14px; " > Handler mainly receives the data sent by the child threads and updates the UI with this data in conjunction with the main thread to interact with the UI main thread. For example
(1)   You can send a message with handler and then receive it in a handler thread, Processing the message to avoid processing transactions directly in the main thread of the UI causing other processing work that affects the main thread of the UI, Android provides handler as the main thread and child thread;
(2) You can also ;
(3) You can also .

Typically, when an application starts, Android first opens a main thread (that is, the UI thread) , and the main thread is a UI control in the admin interface for event distribution. If you need a time-consuming operation at this time, for example: network 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 message Force Close.
this time we need to put these time-consuming operations on a sub-thread, because the child threads involve UI updates, but when there are actions in the child thread that involve manipulating the UI, it can be dangerous to the main thread-that is, the update UI can only be updated in the main thread. Operating in a sub-thread is dangerous. At this time, handler appeared to solve this complex problem, because handler runs in the mainline approached (UI thread), it and the child thread can pass the data through the Message object, at this time, the handler undertakes to accept the child thread to pass over ( The child thread passes the message object with the Sedmessage () method (which contains data), puts the messages into the main thread queue, and updates the UI with the main thread.

Ii. Some features of handler
handler can distribute message objects and runnable objects into the main thread, and each handler instance is bound to the thread that created him (typically in the main thread). That is, after the handler object is initialized, it is bound to the message queue of the process it initializes, so you can take advantage of the Message Queuing that handler contains to make some sequence of operations.

Iii. Some methods of distributing messages in handler
Post (Runnable)
postattime (Runnable,long)
postdelayed (Runnable long)
The Post class method allows you to arrange a Runnable object into the main thread queue
sendemptymessage (int)
sendMessage (Message)
sendmessageattime (Message,long)
sendmessagedelayed (Message,long)
The SendMessage class method allows you to schedule a Message object with data to queue and wait for updates.

iv. Application Examples:
1. Pass the message. Used to accept data sent by a child thread and update the UI with this data in conjunction with the main thread.
in Android, actions for the UI typically need to be placed in the main thread. If there is an action on the UI in the child thread, then it is necessary to send the data message to the message queue as a messages object, then use the handlermessge method in handler to process the transmitted data information and manipulate the UI. The Class SendMessage (Message msg) method implements the operation that sends the message. The Handlemessage method that is overridden when initializing the handler object to receive Messgae and to perform related operations.
2. Pass the Runnable object. Used for Message Queuing that is bound by handler to schedule the execution of different operations.
when the handler object is initialized, the message queue is automatically bound by default. The class Post method enables you to send a Runnable object to a message queue and execute the Run method in the different Runnable objects sequentially, in the same way as the queue mechanism.
In addition, Android CPU allocation of the smallest unit is a thread, handler is generally created in a line thread, so handler and thread are bound to each other, one by one. While Runnable is an interface, thread is a subclass of runnable. So, they're both a process.

 Public classHandleractivityextendsActivity {//declaring a two button control    PrivateButton Startbutton =NULL; PrivateButton Endbutton =NULL; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.main); //gets the object that represents the control based on the ID of the control and sets the appropriate listener for both buttonsStartbutton =(Button) Findviewbyid (R.id.startbutton); Startbutton.setonclicklistener (NewStartbuttonlistener ()); Endbutton=(Button) Findviewbyid (R.id.endbutton); Endbutton.setonclicklistener (NewEndbuttonlistener ()); }    classStartbuttonlistenerImplementsOnclicklistener {@Override Public voidOnClick (View v) {//call handler's Post method to add the thread object that will be executed to the queueHandler.post (Updatethread); }    }    classEndbuttonlistenerImplementsOnclicklistener {@Override Public voidOnClick (View v) {handler.removecallbacks (updatethread); }    }    //Create a Handler objectHandler Handler =NewHandler (); //the action to be performed writes the Run method of the thread objectRunnable Updatethread =NewRunnable () {@Override Public voidrun () {System.out.println ("Updatethread"); //inside the Run method, execute the postdelayed or POST methodHandler.postdelayed (Updatethread, 3000); }    };}

The result of the program is that every 3 seconds, a line of Updatetread is printed on the console. This is because the Updatethread object that implements the Runnable interface enters an empty message queue and is immediately executed by the Run method, and within the Run method, it is sent again into the message queue after 3000ms.

3. Handler and Multithreading
Although the post method sends a class object that implements the Runnable interface, it does not create a new thread , but instead executes the Run method in the object. That is, the operations in the entire run are on the same thread as the main threads . (Verify: http://blog.sina.com.cn/s/blog_78c913e30100uqmf.html)
This does not seem to affect those simple operations. But for long-time operations, there will be "suspended animation." To solve this problem, you need to bind the handler to a new open thread's message queue and process the Runnable objects and messages that pass through the message queue on the other thread.

 Public classHandlerTest2extendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {//TODO auto-generated Method Stub        Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.main); //Prints the ID of the current threadSystem.out.println ("activity-->" +Thread.CurrentThread (). GetId ()); //generate a Handlerthread objectHandlerthread Handlerthread =NewHandlerthread ("Handler_thread"); //before using the Handlerthread Getlooper () method, you must first call the class's start () and open a new thread;Handlerthread.start (); //The Looper obtained by Handlerthread is passed to the handler object, which is the message queue that is bound by the default binding when handler is initialized by Looper in another thread to process the message. //Handlerthread As the name implies is the thread that can handle the message loop, it is a thread that owns Looper, can handle the message loop;//in fact, instead of handler and a thread binding, it is better to say that handler and Looper are one by one corresponding. MyHandler MyHandler =NewMyHandler (Handlerthread.getlooper ()); Message msg=Myhandler.obtainmessage (); //sends MSG to the target object, the so-called target object, which is the handler object that generated the MSG objectBundle B =NewBundle (); B.putint ("Age", 20); B.putstring ("Name", "Jhon");        Msg.setdata (b); Msg.sendtotarget (); //send msg to MyHandler    }    //Defining Classes    classMyHandlerextendsHandler { PublicMyHandler () {} PublicMyHandler (Looper Looper) {Super(Looper); } @Override Public voidhandlemessage (Message msg) {Bundle b=Msg.getdata (); intAge = B.getint ("Age"); String name= b.getstring ("name"); System.out.println (' Age ' + Age + ', name is ' +name); System.out.println ("Handler--->" +Thread.CurrentThread (). GetId ()); System.out.println ("Handlermessage"); }    }}

Thus, when a message is passed using the SendMessage method or the Runnable object is passed using the Post method, it is passed to the message queue in another thread that is bound to the handler object and will be processed in another message queue. The main thread will also continue at the completion of the send operation, without affecting the current operation.
It is important to note that the multithreading used here is not opened by the Runnable object, but by the Threadhandler object. The Runnable object is passed only as an object that encapsulates the operation and does not produce a new thread.

Again, in the UI thread (main thread):

mhandler=New  Handler (); Mhandler.post (new  Runnable () {    void  Run () {        // execute code :     }});

This thread is actually running within the UI thread and does not have a new thread.

A common way to create new threads is to:

Newnew handlerthread ("string"); Thread.Start ();

Related information: http://www.cnblogs.com/playing/archive/2011/03/24/1993583.html

Android Learning Note--handler Usage Summary

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.