Android messaging Mechanism (1)

Source: Internet
Author: User

In Android, messages are often used when information is interacting within or between threads, and these basic things can make it easier and better to architect the system and avoid some low-level errors if we are familiar with its internal principles. Before learning the messaging mechanism in Android, let's look at a few classes related to messages:

1.Message

A Message object, as the name implies, is the class that records message information. There are several more important fields for this class:

A.arg1 and Arg2: We can use two fields to hold the integer value we need to pass, and in the service we can store the service ID.


B.obj: This field is an object type, and we can let the field pass a number of items to the recipient of the message.

C.what: This field can be said to be a message flag, in the message processing, we can according to the different values of this field to do different processing, similar to when we handle the button event, through switch (V.getid ()) to determine which button is clicked.

When using the message, we can create a message instance from the new message (), but Android recommends that we pass Message.obtain () or handler.obtainmessage () Gets the message object. This is not necessarily a straightforward creation of a new instance, but rather a message instance that is immediately available from the pool of messages, and is then fetched and returned to this instance. Conversely, if there is no message instance available in the pool, a new message object is given according to the parameter. By analyzing the source, it is known that the Android system instantiates 10 message objects in a messaging pool by default.

2.MessageQueue

Message Queuing, which holds the data structure of the message object and stores the message according to the "FIFO" principle. Storage is not a meaningful save, but instead the message object is concatenated in a linked list. MessageQueue objects do not need to be created by ourselves, but have looper objects to manage them, and a thread can have at most one MessageQueue. We can get the MessageQueue in the current thread through Looper.myqueue ().

3.Looper

MessageQueue manager, in a thread, if there is a Looper object, there must be a MessageQueue object, and there is only one Looper object and one MessageQueue object. In Android, except the main thread has the default Looper object, other threads have no Looper object by default. If you want our newly created thread to have a Looper object, we should first call the Looper.prepare () method and then call the Looper.loop () method. Typical usage is as follows:

    1. class looperthread extends thread      
    2. {      
    3.     public handler  mHandler;      
    4.     public void run ()       
    5.     {      
    6.         looper.prepare ();      
    7. Li class= "alt" >        //other actions        that need to be handled;
    8.         looper.loop ();      
    9.     }      
    10. }   

If the Looper object exists in our thread, we can get it through Looper.mylooper (), and we can get the Looper object of the main thread in the current application via Looper.getmainlooper (). One thing to note in this place is that if the Looper object is in the main thread of the application, Looper.mylooper () and Looper.getmainlooper () get the same object.

4.Handler

The processor of the message. Through the handler object we can encapsulate the message object and then add the message object to the MessageQueue through SendMessage (msg), and when MessageQueue loops to the message, The Handlemessage () method of the handler object corresponding to the message object is called to process it. Because the messages are processed in the Handlemessage () method, we should write a class that inherits from Handler and then handles the operations we need in Handlemessage ().

  1. /**
  2. *
  3. * @author Coolszy
  4. * @blog Http://blog.csdn.net/coolszy
  5. *
  6. */
  7. public class Messageservice extends Service
  8. {
  9. private static final String TAG = "Messageservice";
  10. private static final int KUKA = 0;
  11. Private Looper Looper;
  12. Private Servicehandler handler;
  13. /**
  14. * Because processing messages is in Handler's Handlemessage () method, we need to write our own class
  15. * Inherit from the handler class, then write the function code we need in Handlemessage ()
  16. * @author Coolszy
  17. *
  18. */
  19. Private Final class Servicehandler extends Handler
  20. {
  21. Public Servicehandler (Looper Looper)
  22. {
  23. Super (Looper);
  24. }
  25. @Override
  26. public void Handlemessage (Message msg)
  27. {
  28. Determine which message is based on what field
  29. Switch (msg.what)
  30. {
  31. Case KUKA:
  32. Gets the obj field of the MSG. We can write the function code we need here.
  33. LOG.I (TAG, "The obj field of msg:" + msg.obj);
  34. Break
  35. Other cases
  36. Default
  37. Break
  38. }
  39. If our service has completed the task, stop the service
  40. Stopself (MSG.ARG1);
  41. }
  42. }
  43. @Override
  44. public void OnCreate ()
  45. {
  46. LOG.I (TAG, "messageservice-->oncreate ()");
  47. Service is run in the main thread by default, and services are typically time consuming, if
  48. In the main thread, it will affect the interaction between the program and the user, so the service
  49. Put in a separate thread to execute
  50. Handlerthread thread = new Handlerthread ("Messagedemothread", Process.thread_priority_background);
  51. Thread.Start ();
  52. Gets the Looper object in the current thread
  53. looper = thread.getlooper ();
  54. Create a handler object and pass the Looper over to make handler,
  55. Looper and MessageQueue Connect
  56. handler = new Servicehandler (Looper);
  57. }
  58. @Override
  59. public int Onstartcommand (Intent Intent, int flags, int startid)
  60. {
  61. LOG.I (TAG, "messageservice-->onstartcommand ()");
  62. Get a message instance from the messaging pool
  63. Message msg = handler.obtainmessage ();
  64. Arg1 the ID of the save thread in the Handlemessage () method
  65. We can stop the service by Stopself (Startid) method
  66. msg.arg1 = Startid;
  67. The Flag of MSG
  68. msg.what = KUKA;
  69. Here I create a Date object that assigns a value to the obj field
  70. In practice we can pass the object we need to handle through obj
  71. Date date = new Date ();
  72. msg.obj = date;
  73. Add MSG to the MessageQueue
  74. Handler.sendmessage (msg);
  75. return start_sticky;
  76. }
  77. @Override
  78. public void OnDestroy ()
  79. {
  80. LOG.I (TAG, "messageservice-->ondestroy ()");
  81. }
  82. @Override
  83. Public IBinder Onbind (Intent Intent)
  84. {
  85. return null;
  86. }
  87. }

Below we analyze how messages are handled in Android by tracking code. First put the test code:

Operation Result:

Note: In the test code we used the Handlerthread class, which is a subclass of thread, which will create the Looper object, which eliminates the hassle of writing our own thread subclasses and creating Looper.

Android messaging Mechanism (1)

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.