The Android system stipulates that some time-consuming operations cannot be performed on the UI thread, which will report a ANR error. So in order to avoid this problem, we need to open a new thread to perform some time-consuming operations, to open a new thread, to execute the time-consuming operation in a new thread, but not to update the UI interface in a sub-thread, so we use Android's handler mechanism to solve this problem.
detailed explanations are as follows:
When the application starts, Android first turns on a main thread (i.e. the UI thread), the main thread is the UI control in the management interface for event distribution, for example, if you click on a button, Android will distribute the event to the button to respond to your action. If you need a time-consuming operation at this time, for example: network read data, or read a large local file, you can not put these operations in the main thread, if you put in the main thread, the interface will appear suspended animation phenomenon, if 5 seconds has not been completed, will receive an error "forced shutdown" on the Android system. This time we need to put these time-consuming operations on a sub-thread, because the child threads involve UI updates, the Android main thread is not secure, that is, the update UI can only be updated in the main thread, and the operations in the child threads are dangerous. At this time, Handler appeared. To solve this complex problem, because handler is running in the mainline approached (UI thread), it and the child thread can pass the data through the message object, and at this time, the handler undertakes to accept the child thread passed over ( The child thread uses the Sedmessage () method to transmit the message object, which contains data, which is placed in the main thread queue and updated with the main thread.
1. Diagram Description:
Use an example to illustrate:
2.XML Code:
1 <Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"2 Xmlns:tools= "Http://schemas.android.com/tools"3 Android:layout_width= "Match_parent"4 Android:layout_height= "Match_parent"5 Android:paddingbottom= "@dimen/activity_vertical_margin"6 Android:paddingleft= "@dimen/activity_horizontal_margin"7 Android:paddingright= "@dimen/activity_horizontal_margin"8 Android:paddingtop= "@dimen/activity_vertical_margin"9 Tools:context=". Mainactivity " >Ten One <TextView A Android:id= "@+id/msg" - Android:layout_width= "Wrap_content" - Android:layout_height= "Wrap_content" /> the - <Button - Android:id= "@+id/btn" - Android:layout_width= "Wrap_content" + Android:layout_height= "Wrap_content" - Android:text= "Update UI interface" /> + A </Relativelayout>
3.java Code:
1 PackageCom.example.handler;2 3 ImportAndroid.os.Bundle;4 ImportAndroid.os.Handler;5 ImportAndroid.os.Message;6 Importandroid.app.Activity;7 ImportAndroid.view.Menu;8 ImportAndroid.view.View;9 ImportAndroid.view.View.OnClickListener;Ten ImportAndroid.widget.Button; One ImportAndroid.widget.TextView; A - Public classMainactivityextendsActivity { - PrivateMythread Mythread; the PrivateTextView Mtextview; - PrivateButton Mbutton; - Public classMyHandlerextendshandler{ - @Override + Public voidhandlemessage (Message msg) { - + //TODO auto-generated Method Stub A Super. Handlemessage (msg); at intCount =Msg.arg1; -String name =(String) msg.obj; - Mtextview.settext (name); - } - } - in Private FinalHandler Handler =NewHandler () { - Public voidhandlemessage (Message msg) { to Super. Handlemessage (msg); +String name =(String) msg.obj; - intm =Msg.arg1; theMtextview.append (name +m); * }; $ };Panax Notoginseng - @Override the protected voidonCreate (Bundle savedinstancestate) { + Super. OnCreate (savedinstancestate); A Setcontentview (r.layout.activity_main); theMtextview = (TextView) This. Findviewbyid (r.id.msg); +Mbutton = (Button) This. Findviewbyid (R.ID.BTN); -Mbutton.setonclicklistener (NewOnclicklistener () { $ @Override $ Public voidOnClick (View arg0) { -Mythread =NewMythread (); - NewThread (Mythread). Start (); the } - });Wuyi } the - Private classMythreadImplementsRunnable { Wu @Override - Public voidrun () { About intCount = 0; $ while(Count >= 20) { - - Try { -Thread.Sleep (500); A}Catch(interruptedexception e) { + //TODO auto-generated Catch block the e.printstacktrace (); - } $Message message = Message.obtain ();//Although it is possible to new a message instance here, it is better not to new. theMESSAGE.ARG1 =count; theMessage.obj = "Tom"; thecount++; the handler.sendmessage (message); - } in } the } the About @Override the Public BooleanOncreateoptionsmenu (Menu menu) { the //inflate the menu; This adds items to the action bar if it is present. the getmenuinflater (). Inflate (R.menu.main, menu); + return true; - } the}
Android Learning----Handler News