Using handler to implement message distribution mechanisms in Android (0)

Source: Internet
Author: User
Tags what parameter

In a previous article on Asynctask, we said at the end that Asynctask is using the handler's message asynchronous processing mechanism to return the results of the operation to the main thread with a message, thereby updating the UI thread.

In our daily development work, Handler is also one of the classes that we often use, so what is the main role of handler?

The main function of Handler is the asynchronous processing mechanism of the message (the message can be some UI update we want to do, or some other invisible operation, such as manipulating the database, etc.), and I believe we all know the concept of async.

To put it simply:

1) from a procedural point of view, when executing a line of code, an asynchronous request (message) is sent, and the program does not need to wait on this line of code, but to continue executing the code.

2) from the user's point of view, the user sent a message, do not need anything to do, just in that silly, and can go to do other things, when the corresponding message is processed, the corresponding result will be processed through the callback mechanism.

Therefore, the asynchronous processing mechanism of handler in Android can provide users with a more reasonable and user-friendly experience. Of course, Android is used handler to achieve, other platform environment, also has its own set of asynchronous implementation mechanism, the same principle, the name is different.

Now that we're doing Android, we're definitely going to take a good look at the use of handler and explore the code architecture behind handler.

First, let's start with a simple example and learn how to use handler.

The code is as follows:

public class Mainactivity extends actionbaractivity {    private static final int msg_id_1 = 1;    private static final int msg_id_2 = 2;    Private Handler Mhandler = new Handler () {public        void Handlemessage (Message msg) {            switch (msg.what) {case            M Sg_id_1:                log.v ("Test", "Toast called from Handler.sendmessage ()");                break;            Case msg_id_2: Break;}}    ;        protected void OnCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Message message = Mhandler.obtainmessage ();        Message.what = msg_id_1;        Mhandler.sendmessage (message);}    }

When we start the program, we can see that in the Logcat, you will see that the following information has been printed:

10-27 15:13:21.382:v/test (9618): Toast called from Handler.sendmessage ()

And that's what we do with msg.what = Msg_id_1 in the handlemessage of handler.

From this simple example, we can summarize the use of handler steps, there are several steps:

1) Create a handler object and implement its handlemessage (Message msg) method, such as in code:

Private Handler Mhandler = new Handler () {

And the implementation of the Handlemessage method one step, we can see, will get a message object.

The message object encapsulates a number of parameters, which are commonly used in the following sections:

A) What parameter: This is an int value, which is often an ID that we use to differentiate the message, such as in the example, we assign the msg_id_1 to Msg.what when creating the message.

b) obj parameter: This is an object. With the obj parameter, you can assign any object to a message and then process it in Handlemessage, which is also a way for handler to pass data in asynchronous processing.

c) arg1, arg2, etc. parameters: above a), B) Two parameters are our most commonly used message parameters, basically also need these two parameters is sufficient, but the message still provides some other fields for us to use, such as ARGX, that is, arguments abbreviation.

2) When the handler object is created, the second step is to create a message object, and there are two ways to create the message object:

2.1) Create a new object directly, with the following code:

Message msg = new Message ()

2.2) Use the Handler.obtainmessage () method, which is the way it is used in the above code, as follows:

Message message = Mhandler.obtainmessage ();

In general, we recommend using the second way, why?

Because an object similar to a message pool is maintained inside the message, when we use handler to distribute message, the message object is not necessarily destroyed immediately, but it is possible to put it in a message pool.

When using the Obtainmessage method of handler, handler will get an existing object from the message pool and initialize its information so that we don't need to re-create an object, waste some memory, in the embedded application, memory is not very large case, This is an optimization of performance.

When creating a message, we can assign a value to the msg.what, so that we can determine what the purpose or purpose of the message is in order to handler the Handlemessage.

Of course, different needs, there must be different treatment, this specific situation specific analysis.

3) When the message is created, we can use Handler's SendMessage to send the message, and then the message is captured by its handler and processed.


Next, let's expand on this example with the following code:

public class Mainactivity extends Actionbaractivity {private static final int msg_id_1 = 1;    private static final int msg_id_2 = 2;            Private Handler Mhandler = new Handler () {public void Handlemessage (Message msg) {switch (msg.what) {                Case MSG_ID_1:LOG.V ("Test", "Toast called from Handler.sendmessage ()");            Break                Case msg_id_2:string str = (String) msg.obj;                LOG.V ("Test", str);            Break        }                    }    };        protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Message message = Mhandler.obtainmessage ();        Message.what = msg_id_1;                Mhandler.sendmessage (message);        Message MSG2 = Mhandler.obtainmessage ();        Msg2.obj = "I ' m String from Message 2";        Msg2.what = msg_id_2;    Mhandler.sendmessage (MSG2); }}

And the corresponding results are as follows:

10-27 15:35:19.168:v/test (12135): Toast called from Handler.sendmessage () 10-27 15:35:19.168:v/test (12135): I ' m String F Rom Message 2

Thus, we can see that, using the obj parameter, we have passed the string object to Handlemessage.


In addition to the SendMessage method, when sending a message, handler can also use the following methods:

    Public Final Boolean sendMessage (Message msg) {return sendmessagedelayed (msg, 0);    Public Final Boolean sendemptymessage (int.) {return sendemptymessagedelayed (what, 0);        Public final Boolean sendemptymessagedelayed (int what, long Delaymillis) {Message msg = Message.obtain ();        Msg.what = what;    Return sendmessagedelayed (msg, delaymillis);        Public final Boolean sendemptymessageattime (int what, long Uptimemillis) {Message msg = Message.obtain ();        Msg.what = what;    Return Sendmessageattime (msg, uptimemillis);            Public Final Boolean sendmessagedelayed (Message msg, long Delaymillis) {if (Delaymillis < 0) {        Delaymillis = 0;    } return Sendmessageattime (MSG, systemclock.uptimemillis () + Delaymillis);        The public boolean sendmessageattime (Message msg, long Uptimemillis) {MessageQueue queue = Mqueue; if (queue = = null) {RUNTIMEEXCEPtion e = new RuntimeException (this + "sendmessageattime () called with no Mqueue");            LOG.W ("Looper", E.getmessage (), E);        return false;    } return Enqueuemessage (Queue, MSG, uptimemillis);        Public Final Boolean sendmessageatfrontofqueue (Message msg) {MessageQueue queue = Mqueue; if (queue = = null) {runtimeexception e = new RuntimeException (this + "Sendmessageattime () Cal            LED with no mqueue ");            LOG.W ("Looper", E.getmessage (), E);        return false;    } return Enqueuemessage (queue, MSG, 0); }

We can see that whether it is sendemptymessage or sendmessage, in fact, ultimately, by calling the Sendmessageattime method, the corresponding message object is put into a MessageQueue.

So why put it in the MessageQueue? How do you put it in the MessageQueue to get back to Handler's handlemessage?

The next article, we will continue to learn.

In this article we will simply introduce how to use handler, a simple example, and simply get started.

End.

Using handler to implement message distribution mechanisms in Android (0)

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.