1. What is handler:
Handler the meaning of "manipulator, manager" in the network, which is used in Android to manage the operation of multi-threaded UI;
2. Why handler appears:
In the Android design mechanism, only the main thread (the one that was moved at the first start of a program) is allowed, because this thread is mostly done with UI-related events, so also called the UI thread.
Modifications to the UI, which is a simplification of the rules, are simplified because the threads are unsafe when the Android UI is operating, in order to avoid thread safety when multiple threads concurrently manipulate the UI
Problem, this simplified rule has emerged.
As a result, the problem arises because only the main thread is allowed to modify the UI, so what if the new thread's operations need to modify the original UI? A common example is if the action of the new thread is to update the UI in TextView
Value, how do I do it?
This is the time for handler to pass the rest between the new thread and the thread (UI thread);
3. Features of Handler:
The main is two:
1) Send the message in the newly started thread;
2) in the main thread to obtain, processing messages;
Seemingly simple, but how to deal with the synchronization problem is a problem, that is, how to grasp the timing of the new thread to send messages and the main thread to process the message time. The solution to this problem is:
A queue called MessageQueue is used between the main thread and the new thread, and the newly started thread sends the message to the MessageQueue associated with it, and then the handler method of the main thread is called
Take the corresponding message from the MessageQueue to process it.
4. Implementation mechanism of Handler
The implementation of handler is mainly based on the following methods:
The method used to read the message is;
void Handlemessage (Message msg), a process that processes messages by overriding this method.
Final Boolean hasmessage (int), which checks whether Message Queuing contains a message with the What property is the specified value.
Final Boolean hasmessage (int What,object object), in which the queue has a specified value and a message for the specified object.
Message Obtainmessage (): Gets messages, classes are overloaded in multiple ways.
The methods used to send messages are:
Sendemptymessage (int): Send an empty message;
Final Boolean sendemptymessagedelayed (int what, long Delaymillis): Specifies the number of milliseconds after which an empty message is sent
Final Boolean sendMessage (Message msg): Send Message now
Final Boolean sendmessagedelayed (Message msg, long Delaymillis) specifies the number of milliseconds after which an empty message is sent
public class Handlertest extends Activity{imageview show;//represents the images downloaded from the network bitmap bitmap; Handler Handler = new Handler () {@Override <span style= "color: #ff0000;" >public void Handlemessage (Message msg) </span>{if (msg.what = = 0x123)//If the message was sent by this program {// Use ImageView to display the picture Show.setimagebitmap (bitmap);}}; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.main); show = (ImageView) Findviewbyid (r.id.show); <span style= "color: #ff0000;" >new Thread () </span>{public void Run () {try{//defines a URL object url url = new URL ("Http://img001.21cnimg.com/photos" + <span style= "White-space:pre" ></span> "/album/20140626/o/c164bdb0b24f59929c2113c0a9910636.jpeg");// Open the input stream for the resource corresponding to the URL InputStream is = Url.openstream ();//parse the picture from InputStream bitmap = Bitmapfactory.decodestream (is);//Send Message , notifies the UI component to display the picture <span style= "color: #ff0000;" >handler.sendemptymessage (0x123); </span>is.close ();} catch (Exception e) {e.printstacktrace ();}}}. Start ();}}
The new process sends an empty message to the main process after parsing the picture from the Web, and then the Handlemessage () method in the main thread is automatically called to update the UI.
5. In-depth understanding of the working mechanism of handler
Above we see a simple handler work process, where handler is defined in the main thread. If handler is defined in a sub-thread, then you can get a deeper understanding of how he works.
Because sometimes we need to pass a message from the main thread to a child thread, and let the child thread handle some of the larger computational tasks, because the application should try to avoid time-consuming operations in the UI thread, or it will
Causes a ANR exception (application not responding). In this case, the role of the main thread and the new thread we have described above has been reversed, the main thread needs to send a message to the new threads, and then the new thread
The processing of the message. In this case, handler needs to be defined in a new thread, in which case some extra work is required.
Let's start by explaining the other components that work with handler:
Looper: Each thread corresponds to a Looper, which is responsible for managing the MessageQueue, removing the message from the queue and handing it over to the handler for processing;
MessageQueue: Responsible for managing the message, receiving the message sent by handler;
Is the whole process of work:
The following is a detailed description of the process of work:
Before creating a handler, you need to create the Looper, which is created in Looper.prepare ();
The MessageQueue is created automatically while the looper is created;
The following creates an handler object
Then call Looper's Loop () method
The following code is an example of a crazy Android handout; The main process sends the upper limit to the child thread calculation 2-the prime number between the upper bound
public class Calprime extends activity{static final String upper_num = "UPPER"; EditText Etnum; Calthread calthread;//defines a thread classes class Calthread extends Thread{<span style= "color: #cc0000;" >public Handler mhandler;</span>public void Run () {<span style= "color: #ff0000;" >looper.prepare (); </span><span style= "color: #ff0000;" >mhandler = new Handler () </span>{//defines the method that processes the message @overridepublic void handlemessage (Message msg) {if (Msg.what = = 0x123) {int upper = Msg.getdata (). GetInt (Upper_num); list<integer> nums = new arraylist<integer> ();//Calculates all prime numbers starting from 2 to upper outer:for (int i = 2; i <= upper; i++) {//With I at 2 starting, to the square root of I for all numbers for (int j = 2; J <= Math.sqrt (i); + j) {//if divisible, indicating that this number is not prime if (I! = 2 && I% J = = 0) {Co Ntinue outer;}} Nums.add (i);} Use Toast to display all prime number Toast.maketext (Calprime.this, nums.tostring (), toast.length_long) that are counted. Show ();}}; <span style= "color: #ff0000;" >looper.loop (); </span>}} @Overridepublic void OnCreate (Bundle savedinstancestate){super.oncreate (savedinstancestate); Setcontentview (r.layout.main); etnum = (EditText) Findviewbyid (R.id.etNum); <span style= "color: #ff0000;" >calthread = new Calthread (); </span>//start a thread <span style= "color: #ff0000;" >calthread.start (); </span>}//provides event handlers for button click events public void Cal (View source) {//Create message <span style= "color:# ff0000; " >message msg = new Message (); </span>msg.what = 0x123; Bundle bundle = new bundle (); Bundle.putint (Upper_num, Integer.parseint (Etnum.gettext (). toString ())); <span style= " Color: #ff0000; " >msg.setdata (bundle); </span>//sends a message to handler in a new thread <span style= "color: #ff0000;" >calthread.mhandler.sendmessage (msg); </span>}}