Android's Handler Chapter

Source: Internet
Author: User

Android's message mechanism mainly refers to the handler operating mechanism, handler operation requires the underlying MessageQueue and Looper support. For kids who have developed Android experience, we are generally using handler to update the UI, updating the UI is only part of the handler usage, and here's a look at Handler's mystery.

So what is handler?

Handler is a set of mechanisms that Android gives us to update the UI, and a set of message handling mechanisms that we can use to send messages through handler and to process messages through it.

There are 4 main uses of handler:

1, SendMessage

2, sendmessagedelayed

3. Post (Runnable)

4, postdelayed (Runnable,long)


SendMessage

public class Mainactivity extends Activity implements View.onclicklistener {private Button btn1;    Private Button btn2; Private Handler Handler = new Handler () {//This way we used more in development, in the main thread to update the UI @Override public void Handlemes            Sage (Message msg) {super.handlemessage (msg);        LOG.V ("HJZ", "executed Handlemessage");    }    };        Private Handler handler1 = new Handler (new Handler.callback () {//Create a callback Callback and implement Handlemessage @Override            public boolean handlemessage (Message msg) {log.v ("HJZ", "performed handlemessage inside Callback"); /** * returns false, stating that the event continues to distribute downward, and continues to call the following Handlemessage method * Returns True, stating that it consumes this event, and that this is the end of the interception function.        Method familiar, good, with viewgroup distribution events very similar to */return false;            }}) {@Override public void Handlemessage (Message msg) {super.handlemessage (msg);        LOG.V ("HJZ", "executed Handlemessage");    }    }; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Initview ();    Setlister ();        } private void Initview () {btn1 = (Button) Findviewbyid (R.ID.BTN1);    BTN2 = (Button) Findviewbyid (R.ID.BTN2);        } private void Setlister () {Btn1.setonclicklistener (this);    Btn2.setonclicklistener (this); } @Override public void OnClick (View v) {switch (V.getid ()) {r.id.btn1:new T Hread (New Runnable () {@Override public void run () {Message                        msg = Handler.obtainmessage ();                        Msg.what = 1;                    Handler.sendmessage (msg);                }}). Start ();            Break Case R.id.btn2:new Thread (new Runnable () {@Override public void run               () {         Message msg = Handler1.obtainmessage ();                        Msg.what = 1;                    Handler1.sendmessage (msg);                }}). Start ();        Break }    }}

Xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android: paddingleft= "@dimen/activity_horizontal_margin"    android:paddingtop= "@dimen/activity_vertical_margin"    android:orientation= "vertical" >    <button        android:id= "@+id/btn1" android:layout_width= "Wrap_        Content "        android:layout_height=" wrap_content "        android:text=" handler "/>    <button        android : id= "@+id/btn2"        android:layout_width= "wrap_content"        android:layout_height= "Wrap_content        " android:text= "Handler1"/></linearlayout>
When Handlemessage return value is False in callback, click Btn1 and btn2 to print the log:
07-19 21:16:31.091 9943-9943/com.example.handlerdemo v/hjz: Performed handlemessage07-19 21:16:34.341 9943-9943/ Com.example.handlerdemo V/HJZ: Executed the callback inside the handlemessage07-19 21:16:34.341 9943-9943/com.example.handlerdemo v/ HJZ: Executed the Handlemessage

When the Handlemessage return value is true in callback, click Btn1 and btn2 print the log:

07-19 21:23:18.991 22980-22980/com.example.handlerdemo v/hjz: Performed handlemessage07-19 21:23:20.901 22980-22980/ Com.example.handlerdemo V/HJZ: Executed the handlemessage inside the callback
The analysis in the above handler1 is also verified from the printed log


Sendmessagedelayed

Case R.ID.BTN1:                new Thread (new Runnable () {                    @Override public                    void Run () {                        Message msg = Handler.obtainmessage ();                        Msg.what = 1;                        /**                         * The first parameter is a message object                         * The second parameter is the delay time (in milliseconds) */                        handler.sendmessagedelayed (msg,1000);                    }                ). Start ();                Break


Post (Runnable)

Private Handler Posthandler = new Handler ();    private void Setpost () {        new Thread (new Runnable () {            @Override public            void Run () {                posthandler.post (new Runnable () {                    @Override public                    void Run () {                        log.v ("Hjz", "Posthandler");}}                    )}        ). Start ();    }

postdelayed (Runnable,long)

Private Handler Postdelayedhandler = new Handler ();    private void setpostdelayed () {        new Thread (new Runnable () {            @Override public            void Run () {                Postdelayedhandler.postdelayed (New Runnable () {                    @Override public                    void Run () {                        log.v ("Hjz", " Postdelayedhandler ");                    }                },1000);            }        ). Start ();    }

Above is the 4 basic usage of handler, if these 4 kinds of follow the source to see, you will find that they will eventually call Sendmessagedelayed (Getpostmessage (R), Delaymillis) This method

Then we'll analyze handler create, and look at the handler constructor

Public Handler () {This        (null, FALSE);    }

Public Handler (Callback Callback, Boolean async) {        if (find_potential_leaks) {            final class<? extends handler& Gt Klass = GetClass ();            if (Klass.isanonymousclass () | | klass.ismemberclass () | | klass.islocalclass ()) &&                    (Klass.getmodifiers () & modifier.static) = = 0) {                log.w (TAG, "the following Handler class should be STATIC or leaks might occur:" +                    Klass.getcanonicalname ());            }        }        Mlooper = Looper.mylooper ();   Gets a Looper object, so when is Looper created?        if (mlooper = = null) {            throw new RuntimeException (                "Can ' t create handler inside thread that have not called Looper.prepare () ");        }        Mqueue = Mlooper.mqueue;        Mcallback = callback;        masynchronous = async;    }
Through the source Activitythread Main method

public static void Main (string[] args) {Trace.tracebegin (Trace.trace_tag_activity_manager, "Activitythreadmain");        Samplingprofilerintegration.start ();  Closeguard defaults to True and can is quite spammy. We//Disable it here, but selectively enable it later (via/strictmode) on debug builds, but using DROPBO        x, not logs.        Closeguard.setenabled (FALSE);        Environment.initforcurrentuser ();        Set The reporter for event logging in Libcore eventlogger.setreporter (New Eventloggingreporter ());        Androidkeystoreprovider.install (); Make sure Trustedcertificatestore looks in the right place for CA certificates final File Configdir = environmen        T.getuserconfigdirectory (Userhandle.myuserid ());          Trustedcertificatestore.setdefaultuserdirectory (Configdir); Looper.preparemainlooper ();//This sentence creates a Looper object, creates a MessageQueue object by Looper construction method, and stores the Looper object in the Threadlocal collection. To obtain the corresponding Looper object when handler is created (note the corresponding LoopeR object can also get looper corresponding MessageQueue object) Activitythread thread = new Activitythread ();        Create Activitythread Object Thread.attach (FALSE);        if (Smainthreadhandler = = null) {Smainthreadhandler = Thread.gethandler (); } if (false) {Looper.mylooper (). setmessagelogging (New Logprinter (Log.debug, "Activit        Ythread "));        }//End of event Activitythreadmain.        Trace.traceend (Trace.trace_tag_activity_manager);        Looper.loop ();    throw new RuntimeException ("Main thread loop unexpectedly exited"); }

Take a look at the above Thread.attach (False) This method, the source code

private void Attach (Boolean system) {scurrentactivitythread = this;        Msystemthread = System;  if (!system) {Viewrootimpl.addfirstdrawhandler (new Runnable () {@Override public                void Run () {ensurejitenabled ();            }            }); Android.ddm.DdmHandleAppName.setAppName ("<pre-initialized>", User            Handle.myuserid ());            Runtimeinit.setapplicationobject (Mappthread.asbinder ());            Final Iactivitymanager mgr = Activitymanagernative.getdefault ();            try {mgr.attachapplication (mappthread);            } catch (RemoteException ex) {//Ignore}//Watch for getting close to heap limit.  Binderinternal.addgcwatcher (New Runnable () {@Override public void run () {if (!msomeactivitieschanged) {return;                   Runtime runtime = Runtime.getruntime ();                    Long Dalvikmax = Runtime.maxmemory ();                    Long dalvikused = Runtime.totalmemory ()-runtime.freememory (); if (Dalvikused > ((3*dalvikmax)/4)) {if (Debug_memory_trim) slog.d (TAG, "Dalvik max=" + (Dalvik max/1024) + "total=" + (Runtime.totalmemory ()/1024) + "use                        D= "+ (dalvikused/1024));                        Msomeactivitieschanged = false;                        try {mgr.releasesomeactivities (mappthread);        } catch (RemoteException e) {}}}); } else {//Don ' t set Application object here--if the system crashes,//We can ' t display an alert            , we just want die die. Android.ddm.DdmHandleAppName.setAppName("System_process", Userhandle.myuserid ());                try {minstrumentation = new instrumentation ();                Contextimpl context = Contextimpl.createappcontext (this, Getsystemcontext (). Mpackageinfo);                Minitialapplication = Context.mPackageInfo.makeApplication (true, null);            Minitialapplication.oncreate (); } catch (Exception e) {throw new RuntimeException ("Unable to instantiate Applicati            On (): "+ e.tostring (), E); }}//Add Dropbox logging to Libcore Dropbox.setreporter (new Dropboxreporter ());//focus on view here Rootimpl.addconfigcallback (New ComponentCallbacks2 () {@Override public void onconfigurationchanged ( Configuration newconfig) {synchronized (Mresourcesmanager) {//We need to apply this C Hange to the resources//immediately, BECAUSE upon returning the view//hierarchy'll be is informed about it. if (mresourcesmanager.applyconfigurationtoresourceslocked (newconfig, NULL)) {//This actually Chan  Ged the resources!                        Tell//Everyone is about it.                                if (mpendingconfiguration = = NULL | | Mpendingconfiguration.isotherseqnewer (Newconfig)) {mpendingconfiguration = newconfig;//through a Han Dler to switch the life cycle of the entire activity and implement the handle stored in MessageQueue sendMessage (h.configuration_changed, Newconfi                         g);            }}}} @Override public void Onlowmemory () {    } @Override public void Ontrimmemory (Int. level) {}}); }

Interested can study the Activitythread in the private class H extends Handler This internal classes, the main implementation of activity-related life cycle switching

Through the analysis of the source code, we know that Looper creation was created when Acitivity started.

The relationship between Looper, MessageQueue and handler

Looper

1, the internal contains a message queue (MessageQueue), all the handler send messages to go this message queue

2, Looper.looper method, is a dead loop, constantly take the message from the MessageQueue, if there is a message to process the message, no message will enter the blocking


MessageQueue

MessageQueue is a message queue that can add messages and can process messages


Handler

Handler internal with Looper, that is, in handler can find Looper inside, find Looper also can find MessageQueue; Send a message in handler It's actually sending a message to the MessageQueue queue.

summarize the relationship between the three : handler is responsible for sending messages, Looper is responsible for receiving handler sent over the message, and directly to the message back to handler itself, MessageQueue is a container to store messages

First, the following will continue to improve





Android's Handler Chapter

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.