Android message mechanism

Source: Internet
Author: User

[Java]View Plaincopyprint?
    1. Online in the form of documents circulated, do not know where the original, thank the original author!

================ simply adjusts the format to share the ===============================================

The message mechanism for Android mainly involves three main classes, namely Handler, Message, Looper; First, a brief introduction to each class, and then a description of how the so-called Android message mechanism is implemented, Finally, an example is given.

First, introduce three related classes

1, handler mainly has two uses: the first is to be able to process or distribute the message on a regular basis, followed by the ability to add an execution of the behavior in other threads to execute,

For the method in handler, you can choose the action you care about to overwrite it, handle the specific business operation, the common is that the processing of the message can overwrite the public voidhandlemessage (parameter) method, You can choose whether or not this message needs to be handled according to the parameters, which are related to the specific parameters. For example, the following code:

[Java]View Plaincopyprint?
  1. Handler Mhandler = new Handler () {
  2. @Override public void Handlemessage (Message msg) {//overwrite Handlemessage method
  3. switch (msg.what) {//based on what type of message received
  4. Case bump_msg:
  5. LOG.V ("handler", "handler====" +msg.arg1); Print the received message
  6. Break ;
  7. Default:
  8. super.handlemessage (msg); //It's best to throw a message to the parent class that you don't need or care about, to avoid losing the message
  9. Break ;
  10. }
  11. }
  12. };



2. Message Android.os.Message

Android.os.Message is to define a messge that contains the necessary description and property data, and this object can be sent to Android.os.Handler processing. Attribute fields: Arg1, arg2, what, obj, ReplyTo, and so on, where arg1 and arg2 are used to hold the integer data; what is used to hold the message; obj is an object of any type; ReplyTo is the message manager. is associated to a handler,handler is the message that is processed. Usually the message object is not directly new, as long as the Obtainmessage method in handler is called to get the message object directly.

3. The Looper class is used primarily for a thread that loops through the messages in the message queue.

Looper is primarily responsible for managing Message Queuing, which is responsible for the dequeue and into row operations of messages.

Second, how is the message mechanism of Android implemented?

1, why to use the message mechanism is mainly to ensure that the security between the threads, and do not need to care about the specific message receiver, so that the message itself and the thread stripping open, so that it is convenient to implement timing, asynchronous and other operations.

2. Message mechanism principle:

Activity <---------------> ehandler<-----> looper<-----> MessageQueue

Intentreceiver <-----> Ehandler <-----> looper<-----> MessageQueue

Figure 1

3, how to achieve? (The process of describing the message flow)

Implementation of the message mechanism requires handler, message, Looper three interaction between the implementation; When thread A needs to send a message to thread B, thread B uses its own looper to instantiate the handler class, which is when the handler object is constructed. Passing the current thread's looper to the handler constructor, handler itself will save a reference to the Looper, and after the handler is constructed, the message object can be instantiated with handler Obtainmessage method. As long as the data to be transmitted to Handler,handler will construct the message object, and the message object is added to the queue. You can then call handler's SendMessage method to send the Message object, Looper put it in the message queue, and finally, when looper know that the message queue is not empty, it loops from the message queue to take the message, Removing the message invokes the Handlemessage method of the handler object that was just instantiated to handle the message, as is the case with the entire message process. (as shown in 1)

Three, the following is a simple example of the message mechanism, the specific code is as follows:

1. The following is a new example of a thread sending a message

Handler itself can not only send messages, but also by post to add an anonymous object to implement the Runnable interface to the message queue, the target receives the message can be called back to the way in its own thread to execute the method body of run, this is handler two typical use way!

[Java]View Plaincopyprint?
  1. Class Nolooperthread extends Thread {
  2. private EventHandler Mnolooperthreadhandler;
  3. public Void Run () {
  4. Looper Mylooper, Mainlooper;
  5. Mylooper= Looper.mylooper (); //Get your own looper
  6. Mainlooper= Looper.getmainlooper (); //Get the looper of your own main
  7. String obj;
  8. if (mylooper = = null) {
  9. Mnolooperthreadhandler = new EventHandler (Mainlooper);
  10. obj= "Nolooperthread have no looper andhandlemessage function executed in main thread!";
  11. }Else
  12. {
  13. Mnolooperthreadhandler = new EventHandler (Mylooper);
  14. Obj= "This was from the nolooperthread self andhandlemessage function executed in nolooperthread!";
  15. }
  16. Mnolooperthreadhandler.removemessages (0); //Clear message Queue
  17. if (false = = postrunnable) {
  18. Message m = Mnolooperthreadhandler.obtainmessage (2, 1, 1, obj); //Generate Message Object
  19. Mnolooperthreadhandler.sendmessage (m); //Send Message
  20. LOG.E (STag, "Nolooperthread ID:" + This.getid ());
  21. }Else {
  22. Mnolooperthreadhandler.post (new Runnable () { ///Adds an implementation of Runnable interface to Message Queuing, this Runnable interface implementation is not  Executes in a thread that is executed in the received thread.
  23. public Void Run () {
  24. Tv.settext ("Update UI through handler post Runnalbe mechanism!");
  25. Nolooerthread.stop ();
  26. }
  27. });
  28. }
  29. }



2. The following is an example of a timed loop sending message, as in the following code:

A detailed explanation of the reference code comments

Handler Handler = new Handler () {//Create processing Object Handler

publicvoid handlemessage (Message msg) {

Switch (msg.what) {

Case MES: {

Final int    N = Mcallbacks.beginbroadcast (); Copy a callback list and mark a status

for (int i = 0; I <N; i++) {

                                                                            try  {

                                                                                        Mcallbacks.getbroadcastitem (i). GetValue (Mmediaplayer01.getcurrentposition ());          //Traverse all callback interfaces                                                ,         &NB Sp             } catch   (Exception e) {

E.printstacktrace ();

}

}

Mcallbacks.finishbroadcast (); State Reset after completion

sendmessagedelayed (Obtainmessage (MES), 1 *);

}

break;

default:

Super. Handlemessage (msg);

}

}

};

Note: The entire Hadlemessage method is quite a nested loop

Iv. Summary:

The so-called messaging mechanism is really simple, and it takes only four steps to implement this mechanism:

1, instantiate Looper (because handler need a looper when instantiating);

2, instantiate handler, here need to overwrite Handlemessage method, processing received message;

3. Instantiate the Message object, invoke the Obtainmessage method of the handler object that has been instantiated, pass the data to the Obtainmessage method, and the Obtainmessage method instantiates a Message object. (You can also send an object that implements the Runnable interface);

4. Call handler's SendMessage method to send a message object that is instantiated well.

The process is the same for each thread, as long as you follow the four steps above to send and receive messages.

Android message mechanism

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.