First, the definition of handler:
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, you can use handler to send a message, and then in the handler thread to receive, process the message, to avoid directly in the UI main thread to handle the transaction caused by the UI main thread of other processing work,Android provides Handler is the link between the main thread and the child thread, or you can pass the handler object to another process to send you events through handler in other processes, and you can send a message through the delay of handler, and you can defer processing of some transactions.
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, and operating in a child thread is dangerous. This time, Handler has emerged to solve this complex problem, because handler is running 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 uses Sedmessage () method to pass the Message object, which contains data, which is placed in the main thread queue and updated with the main thread.
Ii. Some features of handler
Handler can distribute the Message object and the Runnable object into the main thread, each handler instance is bound to create his line approached (typically in the main thread), meaning that after the handler object is initialized, The default is bound to the message queue of the process it initializes, so you can take advantage of the message queues 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, for ui operations usually need to be placed in the main thread. If there is an operation in the child thread about ui, then we need to use the data message as a handler The Handlermessge method processes the transmitted data information and operates ui. Class sendmessagehandler objects Handlemessage method to receive messgae and 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.
1. Public classHandleractivityextendsActivity {2. 3.//declaring a two button control4.PrivateButton Startbutton =NULL; 5.PrivateButton Endbutton =NULL; 6. @Override7. Public voidonCreate (Bundle savedinstancestate) {8.Super. OnCreate (savedinstancestate); 9. Setcontentview (R.layout.main); 10.//gets the object that represents the control based on the ID of the control and sets the appropriate listener for both buttonsOne. Startbutton =(Button) Findviewbyid (R.id.startbutton); Startbutton.setonclicklistener (NewStartbuttonlistener ()); Endbutton =(Button) Findviewbyid (R.id.endbutton); Endbutton.setonclicklistener (NewEndbuttonlistener ()); 15. 16. } 17.classStartbuttonlistenerImplementsonclicklistener{18. 19. @Override20. Public voidOnClick (View v) {21st.//call handler's Post method to add the thread object that will be executed to the queue22. Handler.post (Updatethread); 23. } 24. 25. } 26. 27.classEndbuttonlistenerImplementsonclicklistener{28. 29. @Override30. Public voidOnClick (View v) {31. Handler.removecallbacks (Updatethread); 32. } 33. 34. } 35.//Create a Handler objectHandler Handler =NewHandler (); 37.//the action to be performed writes the Run method of the thread objectRunnable Updatethread =NewRunnable () {39. 40. @Override41. Public voidrun () {System.out.println ("Updatethread"); 43.//inside the Run method, execute the postdelayed or POST methodHandler.postdelayed (Updatethread, 3000); 45. } 46. 47. }; 48.}
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.
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.
1. Public classHandlerTest2extendsActivity {2. 3. @Override4.protected voidonCreate (Bundle savedinstancestate) {5.//TODO auto-generated Method Stub6.Super. OnCreate (savedinstancestate); 7. Setcontentview (R.layout.main); 8.//Prints the ID of the current thread9. System.out.println ("activity-->" +Thread.CurrentThread (). GetId ()); 10.//generate a Handlerthread objectHandlerthread Handlerthread =NewHandlerthread ("Handler_thread"); 12.//before using the Handlerthread Getlooper () method, you must first call the class's start () and open a new thread; 13. Handlerthread.start ();14.//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. 15.//Handlerthread, as the name implies, is the thread that can handle the message loop, which is a thread that has looper16., you can handle the message loop; instead of handler and a thread binding, it's better to say that handler and Looper are17. One by one corresponds to. MyHandler MyHandler =NewMyHandler (Handlerthread.getlooper ()); . Message msg =Myhandler.obtainmessage (); 20.//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"); 24. Msg.setdata (b); Msg.sendtotarget ();//send msg to MyHandler26. } 27. 28.//Defining Classes29.classMyHandlerextendshandler{30. PublicMyHandler () {31. 32. } 33. 34. PublicMyHandler (Looper Looper) {35.Super(Looper); 36. } 37. @Override38. Public voidhandlemessage (Message msg) {Bundle B =Msg.getdata (); 40.intAge = B.getint ("Age"); The. String name = b.getstring ("name"); System.out.println ("Age was" + Age + ", name is" +name); System.out.println ("Handler--->" +Thread.CurrentThread (). GetId ()); System.out.println ("Handlermessage"); 45. } 46. } 47.}
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. They will be processed in a separate 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:
Thread thread = new Thread ();
Thread.Start ();
Handlerthread thread = new Handlerthread ("string");
Thread.Start ();
Handler Usage Summary in Android