PreviousArticleThe following is a brief introduction to the android messaging machine:
1. Create handler in a thread with a message loop;
2. Create a message in another thread, bind it to handler, and send the message through handler;
3. process messages in the handlemessage method of handler.
Here are a few questions:
1. Since handler needs to be created in a thread with a message loop, why do we usually not need to create a message loop when creating a handler?
This is because we usually create handler in the main thread, and the main thread creates a message loop by default, which is encapsulated in the android framework.
2. Which thread executes the handlemessage method, is it the thread that creates the message or the thread that creates the handler?
The answer is to create a handler thread because the thread for creating a handler has a message loop, and the final processing of the message is through the message loop.
3. How do I create handler if it is not in the main thread?
The steps are as follows: 1) create a logoff object for the thread, call logoff. Prepare (); 2) Enable the message loop and call logoff. Loop ();
ExampleCodeAs follows:
Thread thread = new thread (New runnable () {@ overridepublic void run () {// todo auto-generated method stublog. I ("create handler thread:", thread. currentthread (). GETID () + ""); logoff. prepare (); // create loopfinal handler = new handler () {// create handler public void handlemessage (Message MSG) {Switch (MSG. what) {Case 1: log. I ("handle message thread:", thread. currentthread (). GETID () + ""); break ;}}; thread childthread = new thread (New runnable () {@ override public void run () {// todo auto-generated method stub log. I ("create message handler", thread. currentthread (). GETID () + ""); message MSG = message. obtain (handler, 1); MSG. sendtotarget (); // send message}); childthread. start (); logoff. loop (); // enable message loop}); thread. start ();
SlaveProgramThe printed log information can also be used to verify the preceding statement.