Android Message,messagequeue,looper,handler (with example)

Source: Internet
Author: User

A few key concepts


1, MessageQueue: is a data structure, see the name of righteousness, is a message queue, the place to store messages. Each thread can have a maximum of one MessageQueue data structure. when a thread is created, its MessageQueue is not created automatically. A Looper object is typically used to manage the MessageQueue of the thread. When the main thread is created, it creates aA default Looper object, and the creation of the Looper object automatically creates a message Queue. Other non-main thread, does not automatically create looper, when needed, by adjusting theimplemented using the Prepare function.
2. Message: The object that is stored in the messages queue. A message queue contains multiple message. The acquisition of the message instance object, usually using the static method obtain () in the message class, has multiple overloaded versions to choose from, and it does not necessarily create a new instance directly,instead, see if there is an available message instance from the message pool, and there is a direct fetch to return to this instance. If there is no message instance available in the message pool,a Message object is created with the given parameters. When Removemessages () is called, the message is removed from the message queue and placed in the message pool. Except for the abovemethod, you can also get a message instance from the handler object's Obtainmessage ().
3, Looper:is the manager of MessageQueue. Each MessageQueue can not be separated from the Looper, Looper object is created by the prepare function to achieve. At the same time, each Looper objectassociated with a thread. The Looper object of the current thread can be obtained by calling Looper.mylooper ()when you create a Looper object, a MessageQueue object is created at the same time. In addition to the default looper of the main thread, other threads do not have MessageQueue objects by default, so they cannot beaccept the message. If you need to accept, you define a Looper object (via the Prepare function) so that the thread has its own Looper object and MessageQueue data structure. Looper Remove the message from the MessageQueue and leave it to Handler's handlemessage for processing. When processing is complete, call Message.recycle () to put it in the message pool.
4, Handler:the processor of the message, handler, is responsible for encapsulating the information that needs to be passed into a message, by invoking the Obtainmessage () of the handler object;The message is passed to Looper, which is implemented by the handler object's SendMessage (). The message is then placed into the MessageQueue by Looper. when the Looper object sees that the MessageQueue contains a message, it broadcasts it. After the handler object receives the message, the Handlemessage () method of the corresponding handler object is calledto handle it. second, how the message between threads is passed

1, the main thread to send themselves a message


Package test.message; Import Android.app.activity;import android.os.bundle;import Android.os.handler;import Android.os.Looper;import Android.os.message;import Android.view.view;import Android.widget.button;import Android.widget.TextView;    public class Mainactivity extends Activity {private Button btntest;         Private TextView TextView;         Private Handler Handler;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                 Setcontentview (R.layout.main);        btntest = (Button) This.findviewbyid (r.id.btn_01);                 TextView = (TextView) This.findviewbyid (r.id.view_01); Btntest.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (V Iew arg0) {Looper Looper = Looper.getmainlooper ();//The Looper object of the main thread//here with the main thread The Looper object creates a handler,//So the message sent by this handler is passed to the MessageQueue of the main thread.               Handler = new MyHandler (looper);                Handler.removemessages (0); Build the Message object//First parameter: is the message code of your own designation, convenient for handler selectively receive//23rd parameter does not have a meaning//fourth parameter                                 The object that needs to be encapsulated message msg = Handler.obtainmessage (1,1,1, "The main thread has sent Messages"); Handler.sendmessage (msg);    Send Message}});        } class MyHandler extends handler{public MyHandler (Looper Looper) {super (Looper);            } public void Handlemessage (Message msg) {super.handlemessage (msg);        Textview.settext ("I am the main thread of the handler, received the message:" + (String) msg.obj); }    }}

2. Other threads send a message to the main thread


Package test.message; Import Android.app.activity;import android.os.bundle;import Android.os.handler;import Android.os.Looper;import Android.os.message;import Android.view.view;import Android.widget.button;import Android.widget.TextView;    public class Mainactivity extends Activity {private Button btntest;         Private TextView TextView;         Private Handler Handler;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                 Setcontentview (R.layout.main);        btntest = (Button) This.findviewbyid (r.id.btn_01);                 TextView = (TextView) This.findviewbyid (r.id.view_01); Btntest.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (V Iew arg0) {//You can see that a thread is started here to manipulate the encapsulation and sending of messages//so that the original main thread is sent to other threads, simple?               Hehe new MyThread (). Start ();    }        }); } classMyHandler extends handler{public MyHandler (Looper Looper) {super (Looper);            } public void Handlemessage (Message msg) {super.handlemessage (msg);        Textview.settext ("I am the main thread of the handler, received the message:" + (String) msg.obj); }}//Added a thread class MyThread extends thread{public void run () {Looper Looper = L Ooper.getmainlooper ();            The Looper object of the main thread//here creates handler with the Looper object of the main thread,//So the message sent by this handler is passed to the main thread's MessageQueue.             Handler = new MyHandler (looper);            Build the Message object//First parameter: is the message code of your own designation, convenient for handler selectively receive//23rd parameter does not make sense//fourth parameter needs to encapsulate the object                         Message msg = Handler.obtainmessage (1,1,1, "Other threads have sent messages"); Handler.sendmessage (msg); Send Message}}}

3. The main thread sends a message to other threads

Package test.message; Import Android.app.activity;import android.os.bundle;import Android.os.handler;import Android.os.Looper;import Android.os.message;import Android.view.view;import Android.widget.button;import Android.widget.TextView;    public class Mainactivity extends Activity {private Button btntest;         Private TextView TextView;         Private Handler Handler;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                 Setcontentview (R.layout.main);        btntest = (Button) This.findviewbyid (r.id.btn_01);                          TextView = (TextView) This.findviewbyid (r.id.view_01);                    Start thread new MyThread (). Start (); Btntest.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (V Iew arg0) {//This handler is instantiated in the thread//at the time it was started, the Message msg = Handler.obtain was instantiated. Message (1,1,1, "mainlineThe message ") that the process sends;            Handler.sendmessage (msg);    }        });        } class MyHandler extends handler{public MyHandler (Looper Looper) {super (Looper);            } public void Handlemessage (Message msg) {super.handlemessage (msg);        Textview.settext ("I am the main thread of the handler, received the message:" + (String) msg.obj); }} class MyThread extends thread{public void run () {looper.prepare ();//create loop for this thread            Er object, used to receive the message//NOTE: Here the handler is defined in the main thread of the Oh, hehe,//front see directly using the handler object, is not looking for, where to instantiate it? Now you see it??? Oh, at the beginning of the instance can not be, because the thread of the Looper object//does not exist yet.                         can now instantiate//Here Looper.mylooper () is the thread's Looper object handler = new Threadhandler (Looper.mylooper ());            This method, have doubts?            is actually a loop that loops through the MessageQueue messages.            Don't often go to see, how do you know you have new news???         Looper.loop (); }//define the message processing class in the threading class ThrEadhandler extends handler{public threadhandler (Looper Looper) {super (Looper); The public void Handlemessage (message msg) {//Here is a message in the MessageQueue in the thread                                 Line Processing//Here we return to the main thread a message handler = new MyHandler (Looper.getmainlooper ());                                 Message MSG2 = Handler.obtainmessage (1,1,1, "Child thread Received:" + (String) msg.obj);            Handler.sendmessage (MSG2); }        }    }}

4. Other threads send themselves a message
Packagetest.message; Import Android.app.activity;import android.os.bundle;import Android.os.handler;import Android.os.Looper;import Android.os.message;import Android.view.view;import Android.widget.button;import Android.widget.TextView;    public class mainactivity extendsactivity {Privatebutton btntest;         Privatetextview TextView;         Privatehandler handler;        @Override publicvoid onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                 Setcontentview (R.layout.main);        btntest = (Button) This.findviewbyid (r.id.btn_01);                          TextView = (TextView) This.findviewbyid (r.id.view_01); Btntest.setonclicklistener (Newview.onclicklistener () {@Override publicvoid OnClick (Vie               W arg0) {//Start thread Newmythread (). Start ();    }        }); } classmyhandler extendshandler{Publicmyhandler (Looper Looper) {suPer (Looper);            } publicvoid Handlemessage (Message msg) {super.handlemessage (msg);        Textview.settext ((String) msg.obj); }} classmythread extendsthread{publicvoid run () {looper.prepare ();//Create the thread's Loope            R object//here Looper.mylooper () obtained is the Looper object of the thread handler =new Threadhandler (Looper.mylooper ());            Message msg = Handler.obtainmessage (1,1,1, "myself");                         Handler.sendmessage (msg);         Looper.loop (); }//define the message processing class in the thread class Classthreadhandler extendshandler{Publicthreadhandler (Loo            Per Looper) {super (Looper);                } publicvoid handlemessage (Message msg) {//Here the message in MessageQueue in this thread is processed Here we return to the main thread a message//add judgment to see if the thread itself sends the message if (Msg.what ==1 && msg.obj.equals ("I                           Own ")) {              Handler =new MyHandler (Looper.getmainlooper ());                                         Message MSG2 = Handler.obtainmessage (1,1,1, "The main thread: I received a message from myself");                               Handler.sendmessage (MSG2); }             }        }    }}


Android Message,messagequeue,looper,handler (with example)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.