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 main thread of the UI other processing work, Android provides handler as the main thread and child threads of the link You can also pass the handler object to another process to send events through handler in other processes, and you can delay the processing of some transactions by sending a message with the delay of handler.
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. 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 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), that is, after the handler object is initialized, the default is bound to the message queue of the process it initializes, Therefore, you can make use of the message queue contained in handler to establish 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.
&nbsP
Examples of video tutorials:
- public class Handleractivity extends Activity {
- Declaring a two button control
- Private Button Startbutton = null;
- Private Button Endbutton = null;
- @Override
- public void OnCreate (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 buttons
- Startbutton = (Button) Findviewbyid (R.id.startbutton);
- Startbutton.setonclicklistener (New Startbuttonlistener ());
- Endbutton = (Button) Findviewbyid (R.id.endbutton);
- Endbutton.setonclicklistener (New Endbuttonlistener ());
- }
- Class Startbuttonlistener implements onclicklistener{
- @Override
- public void OnClick (View v) {
- Call handler's Post method to add the thread object that will be executed to the queue
- Handler.post (Updatethread);
- }
- }
- Class Endbuttonlistener implements onclicklistener{
- @Override
- public void OnClick (View v) {
- Handler.removecallbacks (Updatethread);
- }
- }
- Create a Handler object
- Handler Handler = new Handler ();
- The action to be performed writes the Run method of the Thread object
- Runnable updatethread = new Runnable () {
- @Override
- public void Run () {
- System.out.println ("Updatethread");
- Inside the Run method, execute the postdelayed or POST method
- Handler.postdelayed (this, 3000);
- }
- };
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.
- public class HandlerTest2 extends Activity {
- @Override
- protected void OnCreate (Bundle savedinstancestate) {
- TODO auto-generated Method Stub
- Super.oncreate (savedinstancestate);
- Setcontentview (R.layout.main);
- Prints the ID of the current thread
- System.out.println ("activity-->" + thread.currentthread (). GetId ());
- Generate a Handlerthread object
- Handlerthread handlerthread = new Handlerthread ("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, which is a thread that has Looper
In fact, you can handle message loops , rather than Handler and a thread binding, rather than saying Handler and Looper is One by one corresponds to.
- MyHandler MyHandler = new MyHandler (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 object
- Bundle B = new bundle ();
- B.putint ("Age", 20);
- B.putstring ("name", "Jhon");
- Msg.setdata (b);
- Msg.sendtotarget (); Send msg to MyHandler
- }
- Defining classes
- Class MyHandler extends handler{
- Public MyHandler () {
- }
- Public MyHandler (Looper Looper) {
- Super (Looper);
- }
- @Override
- public void Handlemessage (Message msg) {
- Bundle B = Msg.getdata ();
- int age = B.getint ("Age");
- 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");
- }
- }
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 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:
Thread thread = new Thread ();
Thread.Start ();
Handlerthread thread = new Handlerthread ("string");
Thread.Start ();
Go Handler Summary in Android