When we are dealing with downloads or other tasks that need to be run for a long time. Assume that the processing function is placed directly in the activity's OnCreate or OnStart. Causes the entire activity to be unresponsive during the run, assuming that the time is too long and the program hangs.
Handler is the ability to put these functions in a single thread to run, and the activity does not affect each other.
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 send a message with handler, and then receive and process the message in a handler thread to avoid handling transactions directly in the main thread of the UI causing other processing work that affects the main thread of the UI, and Android provides handler as the main thread and child thread. You can also pass handler objects to other processes to send events to you through handler in other processes. It is also possible to send a message via handler delay. Ability to defer processing of some transactions.
Explanation: When the application starts, Android first opens a main thread (that is, the UI thread), and the main thread is the UI control in the admin interface for event distribution. For example, if you click on a button,android, the event will be distributed to the button. To affect your operation. Suppose you need a time-consuming operation at this point, such as: networked 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 phenomenon, assuming that 5 seconds is not finished. will receive an error "forced shutdown" on the Android system. This time we need to put these time-consuming operations on a sub-thread, because the child thread involves UI updates, but when the child thread has operations that involve manipulating the UI, it is critical to the main thread, that is, the update UI can only be updated in the main thread, and the operation in the child thread is critical. At this point, handler appears to solve this complex problem, because handler executes in the mainline approached (UI thread), and the child thread can pass the data through the message object, and at this time, the handler undertakes to accept the child thread passed over ( The child thread passes the message object (including data) in the Sedmessage () method, putting the messages into the main thread queue and updating the UI with the main thread.
Ii. Some features of handler
Handler is able to distribute the message object and the Runnable object into the main thread, each handler instance is bound to create his line approached (usually on the main thread), that is, 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 included with handler to make some sequence of operations.
It has two functions: (1): Schedule a message or runnable to run somewhere in a main thread, (2) Schedule an action to run in a different thread
Some ways to distribute messages in handler
Post (Runnable)
Postattime (Runnable,long)
Postdelayed (Runnablelong)
The Post class method agrees that you arrange a runnable object into the main thread queue
Sendemptymessage (int)
SendMessage (Message)
Sendmessageattime (Message,long)
Sendmessagedelayed (Message,long)
SendMessage class method, you agree to arrange a message object with data in the queue
Three, handler simple working principle diagram
Iv. Application Examples:
1. Pass a 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 usually need to be placed in the main thread. Assume that there is an action on the UI in a child thread. Then you need to send the data message as a message object to the queue of messages, and then use the Handlermessge method in handler to process the transmitted data. and manipulate the UI. The SendMessage Class (Messagemsg) 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. The message queue that is used to bind through handler. Schedule the order in which different operations are run.
When the handler object is initialized, it will voluntarily bind the message queue by default. The class post method enables you to send a Runnable object to a message queue and run the Run method in different Runnable objects sequentially, according to the mechanism of the queue.
In addition, the smallest unit of Android CPU allocation is the thread. Handler are usually created on a line thread. Thus handler and thread are bound to each other. One by one accordingly. While Runnable is an interface, thread is a subclass of runnable. So. Both of them are a process.
Mars_androids the code in the video
Package Mars.handler;import Android.app.activity;import Android.os.bundle;import android.os.handler;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public Class Handleractivity extends activity {/** Called when the activity is first created. *///declares two button controls private button STARTB Utton = null;private Button Endbutton = null; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); The object that represents the control is obtained from the control's ID, and the Listener Startbutton = (Button) Findviewbyid (R.id.startbutton) is not set for these two buttons; Startbutton.setonclicklistener (New Startbuttonlistener ()); Endbutton = (Button) Findviewbyid (R.id.endbutton); Endbutton.setonclicklistener (New Endbuttonlistener ()); } class Startbuttonlistener implements onclicklistener{@Overridepublic void OnClick (View v) {//calls the handler post method. Join the thread object that will be running to the queue where Handler.post (Updatethread);} } Class Endbuttonlistener implements onclicklistener{@Overridepublic void OnClick (View v) {handler.removecallbacks ( Updatethread);} }//Create a Handler object Handler Handler = new Handler (); The operation that will be run writes the Run method of the thread object where Runnable updatethread = new Runnable () {@Overridepublic void run () {System.out.println ("Updatet Hread ");//Inside the Run method, run the postdelayed or the Post method handler.postdelayed (Updatethread, 3000);} };}
The execution 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
The Post method even sends a class object that implements the Runnable interface. Instead of creating a new thread, it runs 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 longer-time operations. There will be "suspended animation".
To solve the 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.
Package Mars.handler;import Android.app.activity;import Android.os.bundle;import android.os.handler;import Android.os.handlerthread;import Android.os.looper;import Android.os.message;public class HandlerTest2 extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview (r.layout.main);//Print the IDSystem.out.println of the current thread ("activity-->" + Thread.CurrentThread (). GetId ());//Generate a Handlerthread object. Implements the ability to use Looper to process Message Queuing, which is provided by the Android application framework Handlerthread Handlerthread = new Handlerthread ("Handler_thread");// Before using the Handlerthread Getlooper () method, you must first call start () of the class, Handlerthread.start (),//The Looper obtained by Handlerthread will be passed to the handler object, That is, the message queue that is bound by default when handler is initialized by a looper in another thread is processed. Handlerthread, as the name implies, is the thread that can handle message loops. It is a thread with looper that 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 = new MyHandler (Handlerthread.getlooper ()); Message msg = Myhandler.obtainmessage ();//Send msg to the target object, the so-called target object, is the handler object that generated the MSG object Bundle B = new bundle (); B.putint ("Age", "a"); B.putstring ("Name", "Jhon"); Msg.setdata (b); Msg.sendtotarget ();} Class MyHandler extends Handler{public MyHandler () {}public MyHandler (Looper Looper) {super (Looper);} @Overridepublic void Handlemessage (Message msg) {Bundle b = msg.getdata (); int = 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");}}}
Such When passing messages using the SendMessage method or passing runnable objects using the Post method, they are 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 when the send operation is complete. Does not affect the current operation.
You need to pay attention here. 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.
In the UI thread (main thread):
Mhandler=newhandler ();
Mhandler.post (Newrunnable () {
void Run () {
Run the code:
}
});
This thread is actually executed within the UI thread and does not have a new thread.
A common way to create new threads is to:
Thread thread = Newthread ();
Thread.Start ();
Handlerthreadthread = new Handlerthread ("string");
Thread.Start ();
Handler in Android