Simple introduction to Android handler and message processing mechanisms

Source: Internet
Author: User

When learning an Android thread, using a child thread directly in the UI thread to update the contents of the TextView display will have the following error: Android.view.viewroot$calledfromwrongthreadexception:only the Original thread that created a view hierarchy can touch it views.

The general idea is that only the thread that created the control can update the contents of the control.

In Android, if you want to manipulate the UI, you have to do it in the UI thread, which is the main thread, and we can't create a child thread directly in the UI thread, that's not the way it is implemented:

New New Runnable () {         publicvoid  run () {              textview.settext ("Update");         }            }). Start ();

To implement the content of the update TextView display, the message mechanism should be used: Handler;

The three aspects of a messaging mechanism can also be four:

(1) Looper: A thread can produce a Looper object, which manages the MessageQueue (Message Queuing) of this line thread;

(2) Handler: Use Handler to send the message object to the message queue, or to accept Looper messages from the message queue;

(3) MessageQueue: Used to store the message that the thread put in;

(4) Thread: The UI thread is usually the main thread, and the Android launcher will create a MessageQueue for it;

1.Handler Create message:

Each message needs to be handled by the specified handler, which can be accomplished by creating a message handler.

The Android messaging mechanism introduces a message pool that handler when a message is created, first queries whether there is a message in the message pool, if one is obtained directly from the message pool, or if there is no reinitialization of a message instance.

The advantage of using a message pool is that when a message is not being used, it is not garbage collected, but instead is put into a message pool that can be used the next time handler creates a message, and the message pool improves the reuse of the message object and reduces the number of system garbage collections.

The process of creating a message:

2.Handler sending messages

When the UI main thread initializes the first handler, a looper is created through threadlocal, which corresponds to the UI main thread one by one, and the purpose of using threadlocal is to ensure that each thread creates only one looper. This can view the Android source code;

After the other handler initializes, the first handler creates the Looper, and Looper Initializes a message queue MessageQueue.

At this point, the relationship between the main thread, message loop and message queue is 1:1:1;

Handler, Looper, MessageQueue initialization process

While hander holds a reference to the UI main thread message queue MessageQueue and the message loop looper, the child thread can send the message to the message queue MessageQueue of the UI thread through handler;

3.Handler processing messages

The main thread of the UI queries the message queue UI_MQ through Looper, and the message is removed from the message queue when a message is found;

The message is parsed first, the message's corresponding handler is judged by its parameters, and the message is distributed to the specified handler for processing.

The process by which a child thread communicates through the handler, Looper, and UI main thread:

Let's use an example to update the content of TextView in the UI thread.

Activity_main.xml

<Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:paddingbottom= "@dimen/activity_vertical_margin"Android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"Tools:context= "Com.xiaozhang.handler1.MainActivity" >    <TextViewAndroid:id= "@+id/textview"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"android:gravity= "Center"Android:text= "@string/hello_world" />    <ButtonAndroid:id= "@+id/button"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:layout_below= "@id/textview"Android:text= "button"        />    </Relativelayout>

Mainactivity.java

 PackageCom.xiaozhang.handler1;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {Privatebutton button; PrivateTextView TextView; PrivateHandler Handler; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Button=(Button) Findviewbyid (R.id.button); TextView=(TextView) Findviewbyid (R.id.textview); Button.setonclicklistener (NewButtonlistener ()); Handler=NewMyHandler (); }    classMyHandlerextendsHandler {@Override Public voidhandlemessage (Message msg) {textview.settext (String) msg.obj); }    }    classButtonlistenerImplementsOnclicklistener {@Override Public voidOnClick (View v) {Thread T=NewMyThread ();        T.start (); }    }    classMyThreadextendsThread {@Override Public voidrun () {Try{Thread.Sleep (2 * 1000); } Catch(interruptedexception e) {e.printstacktrace (); } String S= "The message from child thread!"; Message msg=Handler.obtainmessage (); Msg.obj=s;        Handler.sendmessage (msg); }    }}

Note: Inner classes in mainactivity are generally implemented by anonymous internal classes;

For example:

 PackageCom.xiaozhang.handler1;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {Privatebutton button; PrivateTextView TextView; PrivateHandler Handler; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Button=(Button) Findviewbyid (R.id.button); TextView=(TextView) Findviewbyid (R.id.textview); Button.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {NewThread () {@Override Public voidrun () {Try{Thread.Sleep (2 * 1000); } Catch(interruptedexception e) {e.printstacktrace (); } String S= "The message from child thread!"; Message msg=Handler.obtainmessage (); Msg.obj=s;                    Handler.sendmessage (msg);            }}.start ();        }        }); Handler=NewHandler () {@Override Public voidhandlemessage (Message msg) {textview.settext (String) msg.obj);    }        }; }}

I just write it casually, should also be able to improve;

The display effect is:

Then click on button, wait 2 seconds, again to display as:

Article reference and collation from:

http://blog.csdn.net/itachi85/article/details/8035333

Mars video;

Recommended:

Http://www.jb51.net/article/33514.htm

Simple introduction to Android handler and message processing mechanisms

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.