Android Development Notes (handler) and Looper

Source: Internet
Author: User

Android's message processing has three core classes: Looper,handler and message. There's actually a message queue, but MQ is encapsulated in Looper, and we don't deal directly with MQ. Usually we use the most often is the message and handler, if the use of handlerthread or their own implementation of similar handlerthread may also be exposed to looper, and MessageQueue is looper internal use, We cannot instantiate and use the standard SDK (the constructor is package visibility).

In Android, the overall process of message processing is:

(1) First of all, to have the content of the message, we put it into a bundle to store the contents of the message.

(2) This bundle is then used to instantiate a message and use this message as the basic unit for sending messages.

(3) You can then put the message in Looper to loop through the messages.

(4) Since handler has looper instances inside, it is possible to send and process the above message directly through handler.

The above is the basic process of message sending and processing in Android.

the following 1, 2 parts are quoted from http://www.cnblogs.com/codingmyworld/archive/2011/09/14/2174255.html

1, Looper

Looper literally means "circulator", which is designed to make a normal thread into a looper thread . The so-called Looper thread is the thread that loops work. In program development (especially in GUI development), we often need a thread to loop continuously, and once a new task is executed, the execution continues to wait for the next task, which is the looper thread. Creating a Looper thread with the Looper class is simple:

public class Looperthread extends thread {    @Override public    void Run () {        //initializes the current thread to Looper thread        Looper.prepare ();                // ... Other processing, such as instantiation of handler                //Start loop processing Message Queue        looper.loop ();}    }

With the above two lines of core code, your thread will be upgraded to Looper thread!!! Isn't it amazing? Let's slow down and see what each of these two lines of code does.

1) Looper.prepare ()

As you can see, you now have a Looper object in your thread that internally maintains a message queue MQ. Note that a thread can have only one Looper object.

2) Looper.loop ()

When the loop method is called, the Looper thread begins to actually work, and it continuously executes the message (also called the task) that pulls the team header from its own MQ. The upper loop () method can simply conclude that looper is used to process the extracted message in MessageQueue, which is shared by MessageQueue handler and Looper, The message taken is referred to handler for processing. Handler is also able to add a message to the MessageQueue by post or send for looper subsequent removal. Sthreadlocal ensures that the looper is thread-private and that all information is sent and processed in this thread.

Prepare () is used to create a key-value pair for the thread in sthreadlocal that corresponds to the thread looper, and the gethandler created by new handler or handler is obtained from Sthreadlocal.get (). The created handler and Looper shared Messagequeue;loop begin to cycle through the events in the MessageQueue. It is the entire process.

2, Handler

Handler plays the role of adding messages and processing messages to MQ (handling only messages sent by itself), notifying MQ that it is going to perform a task (sendMessage) and performing the task (Handlemessage) at loop to its own. The entire process is asynchronous . Handler is created with a looper associated with it, the default constructor associates the looper of the current thread, but this can be set. After adding handler, the effect is as follows:

As you can see, a thread can have multiple handler, but only one looper!

3. Send and process messages using handler

As mentioned in this article, let's implement a message via handler and then change the color and content of a textview within mainactivity. Specifies flag = = False when red, arg1 = 0;flag = = True when blue, arg1 = 1.

We need to understand that handler is sending messages through a process, so we need to write the process of sending messages into the Runnable.run () method. First we create a new SendMessage implements Runnable class, and then we construct the message:

    @Override public void Run () {while (true) {try {thread.sleep (1000);       Each 1-second start message sends bundle bundle = new bundle ();     Bundles are used to store message content msg = Message.obtain ();                   Instantiate an empty message if (flag) {//If flag is true, indicates that the current color is blue MSG.ARG1 = 0;                   The color should turn red, and the record information is used to send flag = false;                Suppose the current has changed to red bundle.putstring ("text", "My color is Red");                   } else {//if flag is false, indicates that the current color is red MSG.ARG1 = 1;                    The color should turn blue, and the record information is used to send flag = true;                Suppose the current has changed to Blue bundle.putstring ("text", "My color is blue");                            } count++;                   Record the number of color changes msg.arg2 = count; The number of times the color change is stored to send msg.SetData (bundle);           Encapsulates bundles into message handler.sendmessage (msg) to be sent;            Send message via handler} catch (Exception e) {e.printstacktrace (); }        }    }

It is important to note that when we send messages through bundles, where do we send them? Here we need to instantiate a handler within the mainactivity to process the sent message, and use this handler to construct the SendMessage.

Class SendMessage implements runnable{    private Handler Handler;    Static Boolean flag = FALSE;    static int count = 0;    Public SendMessage (Handler Handler) {        this.handler = Handler;    }    @Override public    Void Run () {        while (true) {            try {                thread.sleep ();                 Each 1 seconds starts a message to send               /*-----------------------------------------*/                handler.sendmessage (msg);            } catch ( Exception e) {                e.printstacktrace ();}}}}    

Here is the message processing within the mainactivity, and we inherit handler to create a new message handler for ourselves. Use Message.getdata (). getString (String keyValue) to get the bundle information that we encapsulated in the previous step in the message. Determine the color that needs to be changed by judging the simple int type of arg1 and arg2 that pass in the message. (If the message to be sent is simpler, it can be encapsulated directly into the arg1 or arg2 of the message, and you no longer have to use bundles to send messages).

Class MyHandler extends handler{        @Override public        void Handlemessage (Message msg) {            Textview.settext ( Msg.getdata (). getString ("text") + msg.arg2);            if (msg.arg1 = = 1)                textview.settextcolor (color.blue);            else                Textview.settextcolor (color.red);        }    }

Finally, you can start the SendMessage thread by adding a click event to the button.

public class Mainactivity extends Activity {private button button;    Private TextView TextView;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Button = (button) Findviewbyid (R.id.button);        TextView = (TextView) Findviewbyid (R.id.textview);                Button.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {                Thread thread = new Thread (new SendMessage (New MyHandler ()));            Thread.Start ();    }        }); } class MyHandler extends handler{@Override public void Handlemessage (Message msg) {TextView.            SetText (Msg.getdata (). getString ("text") + msg.arg2);            if (msg.arg1 = = 1) textview.settextcolor (Color.Blue);        else Textview.settextcolor (color.red); }    }}

The complete code is as follows:

Import Android.app.activity;import android.graphics.color;import android.os.bundle;import android.os.Message; Import Android.os.handler;import android.view.view;import android.widget.button;import Android.widget.TextView;    public class Mainactivity extends Activity {private button button;    Private TextView TextView;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Button = (button) Findviewbyid (R.id.button);        TextView = (TextView) Findviewbyid (R.id.textview);                Button.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {                Thread thread = new Thread (new SendMessage (New MyHandler ()));            Thread.Start ();    }        }); } class MyHandler extends handler{@Override public void Handlemessage (Message msg) {TextView. SetText (Msg.getdata (). getString("text") + msg.arg2);            if (msg.arg1 = = 1) textview.settextcolor (Color.Blue);        else Textview.settextcolor (color.red);    }}}class SendMessage implements runnable{private Handler Handler;    Static Boolean flag = FALSE;    static int count = 0;    Public SendMessage (Handler Handler) {this.handler = Handler;                 @Override public void, run () {while (true) {try {thread.sleep (1000);       Each 1-second start message sends bundle bundle = new bundle ();     Bundles are used to store message content msg = Message.obtain ();                   Instantiate an empty message if (flag) {//If flag is true, indicates that the current color is blue MSG.ARG1 = 0;                   The color should turn red, and the record information is used to send flag = false;                Suppose the current has changed to red bundle.putstring ("text", "My color is Red");          } else {//if flag is false, indicates that the current color is red          MSG.ARG1 = 1;                    The color should turn blue, and the record information is used to send flag = true;                Suppose the current has changed to Blue bundle.putstring ("text", "My color is blue");                            } count++;                   Record the number of color changes msg.arg2 = count;                The number of times the color change is stored for sending msg.setdata (bundles);            Encapsulates bundles into message handler.sendmessage (msg) to be sent;            } catch (Exception e) {e.printstacktrace (); }        }    }}

Android Development Notes (handler) and Looper

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.