Android Handler and Looper

Source: Internet
Author: User

After reading so many articles, I finally read it.
References: "1" Android Developer Handler "2"handler role in Android"3" Android Thread Looper Handler relationship "4" Android message processing mechanism (figure + source analysis)--looper,handler,message


1, from the definition of understanding handler
 First of all, a reference to "1" in an English sentence to illustrate the following:     a Handler allows you to send and process  message  and Runnable objects associated with a thread ' s  messagequeue In simple terms, each handler instance is created with an associated Threadsand Threads of the Message Queuing, and handler runs the send and execute message and runnable objects. (if the latter half of the sentence does not understand, OK, please continue to look down)
scheduling messages is accomplished with the post(Runnable)postAtTime(Runnable, long)postDelayed(Runnable, long)sendEmptyMessage(int)sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long)methods.This paragraph simply shows that there are many ways to use it, and the sum is a post () and a SendMessage () method, which is mainly about how to send messages to the message queue. (This paragraph no matter)
thePostversions allow you to enqueueRunnableObjects to being called by the message queue When they is received; theSendMessageVersions allow you to enqueue a Messageobject containing a bundle of data that would be processed by the Handler ' s handleMessage(Message)method (requiring that implement a subclass of Handler).--"essence" this paragraph is mainly said, accept it. The Runnable object of the post will be inserted into the message queue and will then be executed by the associated thread, using theSendMessagewill contain Bundle of Datamessages into the message queue by handleMessage(Message)this function to get its value.
plainly, communication can be implemented in two threads through handler.      Why to useHandler, for example, the main thread of the Android UI is only one, if it is time-consuming to perform network operations in the UI thread, it will affect the flow of the app, and the Android system exists if the app does not respond to the user's actions within 5 seconds, it will be considered to be running smoothly, Pop up the window where the blocker is running.


2. Sample program 2.1 Post Sample program
 public class Nasadaliyimage extends Activity {public Iotdhandler handler;          Private ProgressDialog Dialog;          Private Handler Handlerrun;             @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);             Setcontentview (R.layout.activity_nasa_daliy_image);         Handlerrun =new Handler ();//associate Handler to UI thread Refreshfromfeed (); } private void Refreshfromfeed () {///DoSomething executable UI action Thread th = new Thread () {//New  Thread public void Run () {//Perform time-consuming network operations such as Handlerrun.post (// Post Runnable Object New Runnable () {//Implement Runnable interface public                             void Run () {//override Runnable's Run () method//Perform UI action}            }                    );   }     }; Th.start (); Thread Start}

2.2 SendMessage Sample programAccording to the reference "2" get the following code2.2.1Create the handler implementation class, the inner class in the class where the main UI resides

Class MyHandler extends Handler {public            MyHandler () {            } public           MyHandler (Looper l) {                super (L);//use the Provided Looper instead of the default one.          }           Override the Handlemessage method, accept the data, and update the UI          @Override public           void Handlemessage (Message msg) {                super.handlemessage ( msg);                Here the UI action is based on the MSG content         }      }     //execute MyHandler handler = new MyHandler () in the UI thread, and the UI thread will be managed by default without parameters.


    2.2.2 implementation of child threads

Class MyThread implements Runnable {public                void run () {                    //execute time-consuming operation                    Message msg = new Message ();                   Bundle B = new bundle ();                  B.putstring ("cmd", "Update");                   Msg.setdata (b);                   MainActivity.this.myHandler.sendMessage (msg);//Notify handler to update UI   mainactivity for its main thread              }           }


   3. Android Thread Looper Handler Relationship

References "3" are as follows: Thread, a thread is a concurrent the unit of execution thread is a concurrent execution unit.

Looper, Class used to run a messages loop for a thread. Maintains the thread's message loop class.
Handler, A Handler allows you to send and process Message and Runnable objects associated with A thread ' s MESSAGEQ Ueue. Sends a message (Runnable object) to a message queue, or executes a Message Queuing message (Runnable object).
See the relationship between the three (image from "4"):


From there, you can see that a looper is included in a main thread, and Looper contains a message queue that associates a handler MyHandler to the main threadIn the worker thread, SendMessage or post to the message queue, which is then removed by the Looper that manages the message queue, and if runnable is executed, if it is a messagecall the corresponding handler of theHandlemessageto get.

Below is a description of the next Looper


The Looper Startup example program is as follows:

public class Looperthread extends Thread {    private Handler handler1;    Private Handler Handler2;    @Override public    Void Run () {        //initializes the current thread to Looper thread        looper.prepare ();                Instantiation of two Handler        handler1 = new Handler ();        Handler2 = new Handler ();                Start loop processing Message Queue        looper.loop ();}    }


where the app launches the activity source code also has the corresponding codes:

Activitythread.java public static final void main (string[] args) {    looper.preparemainlooper ();    Activitythread thread = new Activitythread ();        Thread.attach (false);        This closes the message loop        Looper.loop ();}

Which Looper. Loop () ; is the looper constantly reading messages in the queue

after that, the following code can be seen in the public static void loop () in \sdk\sources\android-16\android\os\ 's Looper.java, referring to "4"gets the message, and by calling the DispatchMessage(msg) function to process messages

public static final void loop () {Looper me = Mylooper ();  Get current thread looper MessageQueue queue = Me.mqueue;        Get the current Looper MQ//These two lines do not understand = = but do not affect the understanding of binder.clearcallingidentity ();        Final Long ident = Binder.clearcallingidentity ();                Start loop while (true) {message msg = Queue.next ();//Remove Message if (msg! = null) {                if (Msg.target = = null) {//message has no target for end signal, exit loop return;                }//Log ... if (me.mlogging!= null) me.mLogging.println (">>>>> dispatching to" + Msg.target +                "+ Msg.callback +": "+ msg.what); Very IMPORTANT!                Give the real processing work to the target of the message, that is, the handler msg.target.dispatchMessage (msg) to be spoken later;                or the log ... if (me.mlogging!= null) me.mLogging.println ("<<<<< finished to "+ Msg.target +" "+ msg.callback);                The following does not understand, the same does not affect the understanding of the final long newident = Binder.clearcallingidentity ();                            if (ident! = newident) {log.wtf ("Looper", "Thread identity changed from 0x"                            + long.tohexstring (ident) + "to 0x" + long.tohexstring (newident) + "when dispatching to" + Msg.target.getClass (). GetName () + "" + Msg.callback + "what=" + M                Sg.what);            }//Recycle message Resource msg.recycle (); }        }    }


Check again at\sdk\sources\android-16\android\os\handler.java in thedispatchmessage function, execute runnable or callhandlemessage for processing.


Process message, the method is called by Looper public    void DispatchMessage (Message msg) {        if (msg.callback! = null) {            // If message is set to callback, that is, runnable messages, processing callback!            handlecallback (msg);        } else {            //If handler itself is set callback, then callback            if (mcallback! = null) {/                 * This approach allows the Handler.callback interface to be implemented by the activity and so on, avoiding writing the handler rewrite Handlemessage method.                if (Mcallback.handlemessage (msg)) {                    return;                }            }            If the message has no callback, call handler's Hook method handlemessage            handlemessage (msg);}    }        Process runnable message    private final void handlecallback (Message message) {        message.callback.run ();  Call the Run method directly!    }    Hook method implemented by subclass public    void Handlemessage (Message msg) {    }


References: "1" Android Developer Handler "2"handler role in Android"3" Android Thread Looper Handler relationship "4" Android message processing mechanism (figure + source analysis)--looper,handler,message






Android Handler and Looper

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.