Can be used to solve the problem that the Workerthread cannot modify the UI control as mentioned in the previous note
I. Basic principles of Handler, Looper and MessageQueue
Handler puts the message object into the MessageQueue, and Looper is responsible for constantly extracting the message object from the message queue header. The removed object is then handed to handler for processing.
Second Simple Handler Example
-Create a class that inherits Handler first, Note that importing Android.os.Handler (very important)
Class Firsthandler extends handler{}
-Replication Method Handlemessage (Message msg)
-Create Handler Object
Handler = Firsthandler ()
-Generates a message and assigns a value to the What member variable
Message msg = Handler.obtainmessage ();
Msg.what = 2;
-Place the Message object in the message queue.
Handler.sendmessage (msg);
-looper will remove the message object from the message queue;
-looper will find the handler docking corresponding to the message object (each Message object has a corresponding handler object);
-looper will invoke the Handlemessage (message msg) method of the Handler object to process the message object.
Third, the realization of the Haandler Handlemessage () method in the main thread
Note: Messages can be sent either in Workerthread or in Mainthread, that is: handler.sendmessage (Message msg)
1) Send a message in the run () of the new thread:
class extends thread{ @Override publicvoid run () { = "simulates data obtained from the network"; = handler.obtainmessage (); = S; Handler.sendmessage (msg); } }
2) the Carbon handlemessage () method. Because this method is called by the main thread, you can change the UI.
class extends handler{ @Override publicvoid handlemessage (Message msg) { = ( String) Msg.obj; Textview.settext (s); }}
Android Learning Note (13) Handler