Learn more about the source code of the message in Android

Source: Internet
Author: User

I believe that everyone on the Android handler is familiar, but to know, handler on its own is only a shell, the real role in the internal function is the message class, for message this class, I believe we will not be unfamiliar, As you often use the Message.obtain () method. But do you know what the obtain () method does for us, and below I will lead you to the Kingdom of the message, to find out.

The first thing you'll be greeted with is this line of code:

[Java]View Plaincopyprint?
    1. Public Final class Message implements Parcelable


Needless to say, the message implements the Parcelable interface, which means that the data encapsulated by the message can be transmitted through the intent and IPC. Now that the Parcelable interface is implemented, the three methods required in the message method: 1) Writetoparcel 2) describecontents 3) Createfromparcel.

The following four member variables we need to focus on are:

1) public int

2) public int arg1

3) public int arg2

4) Public Object obj


We often use a few of these parameters, but do their true meanings really understand? As long as Google's internal comments are truly reliable.

1) User-defined message identification code, so that the system can identify the current message is about what. Since each handle has its own namespace for the ID of its own message. So we don't have to worry about the conflict between the various handler.

2) where the second parameter is the same as the meaning of the third parameter, the note shows that the two parameters, if the user simply needs to transfer simple int type data, compared to SetData (bundle bundle), the cost is lower.

3) The fourth parameter, as described in the note, is understood as follows: This is a random data sent to the recipient, if the use of Messager to send data for cross-process communication, then the current obj if the implementation of parcelable must not be null pointer, For the transmission of other data, we generally use the SetData method. However, it is important to note that for versions higher than Android.os.build.version_codes#froyo, the parcelable objects here are not supported.


After the above variables are finished, we need to explain the definition of another set of constants:

[Java]View Plaincopyprint?
    1. private static  final object spoolsync = new object ();   
    2. private  static message spool;  
    3. private  static int spoolsize =  0;  
    4. //the largest size    in the pond;
    5. private static  Final int max_pool_size = 50;  


At first glance, you may not understand the definition of the above four variables, if I remind you that the message in Android can be reused, then I believe you can roughly guess the meaning of these four variables.

1, the first variable is actually acting as a lock, to avoid multi-threaded scramble for resources, resulting in dirty data

2. Spool this variable can be interpreted as a pointer to the head of a message queue

3, Spoolsize is the length of the current message queue

4. Defines the maximum length of Message Queuing cache messages.


Ok, here, the member variables of the message have been explained, the next main is to explain the API method.

The first method is the obtain method that you often use, without any parameters:

[Java]View Plaincopyprint?
  1. Public static Message obtain () {
  2. synchronized (spoolsync) {
  3. if (sPool! = null) {
  4. Message m = sPool;
  5. SPool = M.next;
  6. M.next = null;
  7. spoolsize--;
  8. return m;
  9. }
  10. }
  11. return new Custommessage ();
  12. }

First, in order to avoid multi-threading to scramble for resources, Spoolsync to lock. First, determine if the current queue pointer is empty, if the current pointer is not empty, the current queue header message can be reused and taken out, then the current queue of the head pointer to the current message of the next message, that is, M.next, at the same time, the trailing pointer of the extracted message is set to NULL, The length of the queue is reduced by 1.

A second method:

[Java]View Plaincopyprint?
  1. Public static message obtain (message orig) {
  2. Message m = obtain ();
  3. M.what = Orig.what;
  4. M.ARG1 = ORIG.ARG1;
  5. M.ARG2 = ORIG.ARG2;
  6. M.obj = Orig.obj;
  7. M.replyto = Orig.replyto;
  8. if (orig.data! = null) {
  9. M.data = new Bundle (Orig.data);
  10. }
  11. M.target = Orig.target;
  12. M.callback = Orig.callback;
  13. return m;
  14. }

As we can see, this method has a orig parameter compared to the above method, and from the above code we can see that the object of the message is taken out of the queue first, then the individual data of the object in which the parameter is copied, and finally the object is returned.

The third method is as follows:

[Java]View Plaincopyprint?
    1. Public static Message obtain (Handler h) {
    2. Message m = obtain ();
    3. M.target = h;
    4. return m;
    5. }

Needless to say, this function specifies a handler object for the currently created message because we know that handler is the final destination of the message.

[Java]View Plaincopyprint?
    1. Public static Message obtain (Handler H, Runnable callback) {
    2. Message m = obtain ();
    3. M.target = h;
    4. M.callback = callback;
    5. return m;
    6. }

Compared to the above method, there is a line M.callback = callback, according to the note above, when some messages are actually executed, callback this Runnbale method will be triggered execution.

Then there is the logic of a series of methods that are similar, and we take one of them to explain:

[Java]View Plaincopyprint?
  1. Public static Message obtain (Handler H, int. What, int arg1, int arg2) {
  2. Message m = obtain ();
  3. M.target = h;
  4. M.what = what;
  5. M.ARG1 = arg1;
  6. M.ARG2 = arg2;
  7. return m;
  8. }

This means that when you create a message, you can provide some logically needed arguments for the message.

Message is created, then there must be a concept of recycling, let's look at:

[Java]View Plaincopyprint?
  1. Public void Recycle () {
  2. Clearforrecycle ();
  3. synchronized (spoolsync) {
  4. if (Spoolsize < max_pool_size) {
  5. Next = SPool;
  6. SPool = this ;
  7. spoolsize++;
  8. }
  9. }
  10. }
  11. <pre name="code" class="java" >void Clearforrecycle () {
  12. Flags = 0;
  13. what = 0;
  14. Arg1 = 0;
  15. Arg2 = 0;
  16. obj = null;
  17. ReplyTo = null;
  18. when = 0;
  19. target = null;
  20. callback = null;
  21. data = null;
  22. }



In Clearforrecycle, this function is to do some preprocessing of the recovery, the parameter set to 0 is set to 0, the null parameter is set to NULL. In the Recycle function, the current message is added to the end of the queue as long as the current cached queue length does not exceed the upper limit.

The following methods are required to implement parcelable:

[Java]View Plaincopyprint?
  1. Public static final parcelable.creator<custommessage> Creator
  2. = New Parcelable.creator<custommessage> () {
  3. Public Message Createfromparcel (Parcel source) {
  4. Message msg = Message.obtain ();
  5. Msg.readfromparcel (source);
  6. return msg;
  7. }
  8. Public message[] NewArray (int size) {
  9. return new message[size];
  10. }
  11. };
  12. public int describecontents () {
  13. return 0;
  14. }
  15. public void Writetoparcel (Parcel dest, int flags) {
  16. if (callback! = null) {
  17. throw New RuntimeException (
  18. "Can ' t marshal callbacks across processes.");
  19. }
  20. Dest.writeint (what);
  21. Dest.writeint (ARG1);
  22. Dest.writeint (ARG2);
  23. if (obj! = null) {
  24. try {
  25. Parcelable p = (parcelable) obj;
  26. Dest.writeint (1);
  27. Dest.writeparcelable (P, flags);
  28. } catch (ClassCastException e) {
  29. throw New RuntimeException (
  30. "Can ' t marshal non-parcelable objects across processes.");
  31. }
  32. } Else {
  33. Dest.writeint (0);
  34. }
  35. Dest.writelong (when);
  36. Dest.writebundle (data);
  37. Messenger.writemessengerornulltoparcel (ReplyTo, dest);
  38. }
  39. private void Readfromparcel (Parcel source) {
  40. what = Source.readint ();
  41. Arg1 = Source.readint ();
  42. Arg2 = Source.readint ();
  43. if (source.readint ()! = 0) {
  44. obj = source.readparcelable (GetClass (). getClassLoader ());
  45. }
  46. when = Source.readlong ();
  47. data = Source.readbundle ();
  48. ReplyTo = Messenger.readmessengerornullfromparcel (source);
  49. }

Ok,message of the core source of the analysis is explained here

Learn more about the source code of the message in Android

Related Article

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.