To learn about thread interaction in Android, you must master the four concepts of thread, logoff, messagequeue, and handler.
1. Thread indicates a thread. Not every thread has a logoff, but the logoff must be attached to a thread.
2. logoff maintains a messagequeue, that is, the message queue.
3. Each messagequeue has a handler. The Handler object is used to send messages to messagequeue or receive messages sent by loler (from messagequeue.
Obtain logoff object reference:
Looper looper = Looper.myLooper();
To communicate with lofter, we need to build a handler subclass. Here we name it eventhandler.
Eventhandler is responsible for accessing messagequeue.
By eventhandler, we can send a message to logoff and put it in its messagequeue.
Class eventhandler extends handler {public eventhandler (Looper loader) {super (logoff) ;}@ override public void handlemessage (Message MSG) {// process received message textview. settext (string) MSG. OBJ );}}
Send a message:
Eventhandler handler = new eventhandler (logoff); handler. removemessages (); // clear the event string STR = "Hello, message. "; message MSG = handler. obtainmessage (1, 1, 1, STR); // assemble an event handler. sendmessage (MSG); // send an event
To send a message to the main thread in another thread, you can use the following method to obtain the logoff object reference of the main thread:
Looper mainloler = Looper. getmainlooper (); // obtain handler next. The code for sending the message is the same as before.