What is Handler
As I said before, Android does not allow threads (workerthread) outside the main thread (Mainthread) to modify the UI components, but does not put all the update UI operations in the main thread (which can cause ANR). Then only a single child thread (Workerthread) can be started to process, after processing is completed, the results are notified to the UI main thread, the child thread and the main thread of communication to use the handler.
Fundamentals of Handler, Looper and MessageQueue
Let's take a look at their duties:
handler--handler, responsible for sending and handling message.
messagequeue--Message Queuing, used to hold messages sent by Handler, uses FIFO (first in first out) rules to concatenate the message in a linked list, waiting for looper to be extracted.
looper--message pump, constantly take messages out of message queue and pass it back to handler
1. Handler object calls the Obtainmessage () method to get the message object
2. Call the SendMessage (Message msg) method to send the message to the message queue (MessageQueue)
3. Looper Loop This removes the MSG from the message queue
4. Call the Handlemessage (Message msg) method of the handler object to pass the extracted msg to handler
Handler the message to the queue, Looper gets the message from the queue and then passes it to handler, which seems like a hard work, and we look at it through the code.
Packagecn.lixyz.handlertest;Importandroid.app.Activity;Importandroid.graphics.drawable.BitmapDrawable;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.ImageView;/*** Implement click button to start the slideshow, each slide interval 2s. */ Public classMainactivityextendsActivity {Privatebutton button; PrivateHandler Handler; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Button=(Button) Findviewbyid (R.id.button); Handler=NewMyHandler (); Button.setonclicklistener (NewButtononclicklistener ()); } classButtononclicklistenerImplementsView.onclicklistener {@Override Public voidOnClick (View v) {Thread T=NewChangepicthread (); T.start (); } } classChangepicthreadextendsThread {@Override Public voidrun () {Super. Run (); Try{Thread.Sleep (1 * 1000); LOG.D ("Ttttt", "---->" +Thread.CurrentThread (). GetName ()); Message msg=Handler.obtainmessage (); Msg.what= 100; Handler.sendmessage (msg); } Catch(interruptedexception e) {e.printstacktrace (); } } } //Create an inner class, inherit handler, to create a handle object classMyHandlerextendsHandler {@Override Public voidhandlemessage (Message msg) {Super. Handlemessage (msg); LOG.D ("Ttttt", "====>" +Thread.CurrentThread (). GetName ()); inti =Msg.what; LOG.D ("Ttttt", "message=" +i); } }}
Mainactivity.java
<linearlayout xmlns: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:orientation = "vertical" Tools:context =". Mainactivity "> <button android:id =" @+id/button " Android:layout_width = "Wrap_content" Android:layout_height =" Wra P_content " android:layout_gravity =" center " = "30DP" Android:text =" SendMessage "/>< /linearlayout>
Activity_main.xml
Click the button to view the log
09-16 10:55:12.064 12614-12669/cn.lixyz.handlertest d/ttttt:---->thread-21309-16 10:55:12.064 12614-12614/cn.lixyz.handlertest d/ttttt:====>main09-16 10:55:12.064 12614-12614/ Cn.lixyz.handlertest d/ttttt:message=100
As you can see, Changepicthread's thread name is Thread-213,myhandler's thread name is main, and that message is passed over, so we can not handle what we need to do in the threads and pass the result to handler. Handler to modify the UI?
A simple example of handler
Click the button to start playing the slideshow.
Packagecn.lixyz.handlertest;Importandroid.app.Activity;Importandroid.graphics.drawable.BitmapDrawable;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.ImageView;/*** Implement click button to start the slideshow, each slide interval 2s. */ Public classMainactivityextendsActivity {PrivateImageView ImageView; Privatebutton button; PrivateHandler Handler; Private int[] Images ={r.drawable.pic1, R.drawable.pic2, R.DRAWABLE.PIC3, R.drawable.pic4, R.drawable.pic5, R.DRAWABLE.PIC6,}; Private intindex = 0; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Button=(Button) Findviewbyid (R.id.button); ImageView=(ImageView) Findviewbyid (R.id.imageview); Handler=NewMyHandler (); Button.setonclicklistener (NewButtononclicklistener ()); } //create an internal class that implements the Onclicklistener interface for registering listener button start Events classButtononclicklistenerImplementsView.onclicklistener {@Override Public voidOnClick (View v) {Thread T=NewChangepicthread (); T.start (); } } //Create an inner class, the user performs a 2s transform slide classChangepicthreadextendsThread {@Override Public voidrun () {Super. Run (); Try { while(true) {Object obj=NewObject (); synchronized(obj) {Message msg=Handler.obtainmessage (); Msg.obj=index; Handler.sendmessage (msg); Index++; Thread.Sleep (2 * 1000); if(Index >=images.length) {index= 0; } } } } Catch(interruptedexception e) {e.printstacktrace (); } } } // classMyHandlerextendsHandler {@Override Public voidhandlemessage (Message msg) {Super. Handlemessage (msg); inti = (int) Msg.obj; bitmapdrawable BD=(bitmapdrawable) imageview.getdrawable (); if(BD! =NULL&&!Bd.getbitmap (). isRecycled ()) {Bd.getbitmap (). Recycle (); } imageview.setimageresource (Images[i]); } }}
Mainactivity.java
<LinearLayoutxmlns: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:orientation= "vertical"Tools:context=". Mainactivity "> <ImageViewAndroid:id= "@+id/imageview"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content" /> <ButtonAndroid:id= "@+id/button"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_gravity= "Center"Android:layout_margintop= "30DP"Android:text= "Click to play" /></LinearLayout>
Activity_main.xml
Android Note (30) asynchronous update in Android (ii) Handler