Android's Handler

Source: Internet
Author: User
Tags message queue

The basic usage and operating principle of handler in Android.

A recent video of the Mars Android Reset version of the second quarter of the handler, let me for this previously know how to use, but do not understand the principle of the components of the understanding of the moment deepened without several times. Mars is really good, the video is really pretty good. Below I write the knowledge that I have learned, as well as my own understanding.

    1. Basic operating principle of handler
    2. Handler how to transfer data from worker thread to main thread
    3. Handler how to transfer data from main thread to worker thread
    4. Handler's post () method
Basic operating principle of handler

Why do we need a handler? I think this is one of the most important questions, that is, what is the role of handler? Handler is primarily used for inter-thread communication, so the question comes again, why do you need multiple threads in an app instead of just one UI thread?

If there is only one UI thread in the app, then when a network connection is required and the network downloads these long-awaited tasks, the Android system detects that the UI main thread is not responding for a long time and emits a application not response exception warning. Referred to as the ANR problem. Therefore, in the main thread of the UI, to interact with the user in real time, there is no long waiting problem. As a result, these tasks must be done in worker thread.

However, depending on the Android settings, threads other than the main thread of the UI (except for special controls such as ProgressBar) cannot modify the controls in the UI, so that new problems arise, and we interact with the user on the UI of the data that the child thread obtains, how it reacts? In this way, there is this ingenious component, handler!

So, how exactly does handler work? The handler object first takes out a message object, deposits it into a message queue MessageQueue, and then at the other end, there is an Looper object, which iterates over the message queue and gives it to handler to process.

Handler how to transfer data from worker thread to main thread
public class Mainactivity extends Actionbaractivity {private Handler Handler;    Private button button;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Button = (button) Findviewbyid (R.id.canclebutton);//Click button to start the new thread Button.setonclicklistener (onclicklistener                () {public void OnClick (View arg0) {thread thread = new Mythread ();            Thread.Start ();        }        });    Handler = new MyHandler (); }//the Handlermessage method in the replication Hanlder, processing the message received from the Message Queue class MyHandler extends handler{@Override public void Han            Dlemessage (Message msg) {super.handlemessage (msg);            String s = msg.obj.toString ();        System.out.println ("In the current Thread" +thread.currentthread (). GetName () + "Get messages from this thread" +s); }//uses the Handler.obtainmessage () method in the worker thread to get a message object, and then it is sent to message queue CLass Mythread extends thread{@Override public void Run () {Message msg = Handler.obtainmessage ()            ;            Msg.obj = CurrentThread (). GetName ();        Handler.sendmessage (msg); }    }}

From this example, we can see that the Handlermessage () method is running in the main thread, and he can get a message from the worker thread, so that the message can be updated in the UI interface.

Why is it that the Handlemessage method is called automatically when a handler object is initialized? Because there is a Looper object in the Android.os.Handler class that iterates through the message queue and calls Handlem instead of a method.

Handler how to transfer data from main thread to worker thread
public class Mainactivity extends Actionbaractivity {private Handler Handler;    Private button button;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Button = (button) Findviewbyid (R.id.canclebutton);//A button is clicked and a message is sent to the worker thread Button.setonclicklisten ER (new Onclicklistener () {public void OnClick (View arg0) {////Use the Handler.obtainmessage () method in main to get a                Message object, and then messages are sent into message queue msg = Handler.obtainmessage ();                Msg.obj = Thread.CurrentThread (). GetName ();            Handler.sendmessage (msg);        }        });        Thread thread = new Mythread ();    Thread.Start (); }//the Handlermessage method in the replication Hanlder, processing the resulting message class MyHandler extends handler{@Override public void Handlemes            Sage (Message msg) {super.handlemessage (msg); String s = msg.oBj.tostring ();        System.out.println ("In the current Thread" +thread.currentthread (). GetName () + "Get messages from this thread" +s); The}//work thread accepts this message and calls the Handlemeesage () method to process the message class Mythread extends thread{@Override public voi            The loop method of the D run () {///Looper object removes the message from the message queue and calls the Handlemeesage () method to process the message looper.prepare ();            Handler = new MyHandler ();        Looper.loop (); }    }}

By running the results, it is known that the Handlemessage () method runs in worker thread so that messages from the main thread can be processed in the worker thread, enabling interprocess communication.

Handler's post () method

The Post method executes the Runnable object in the main thread by generating a message, then placing the Runnable object in the message, and then placing it in the queue of messages, and then extracting it from the main thread.

public class Mainactivity extends Actionbaractivity {private Handler Handler;    Private button button;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);      Button = (button) Findviewbyid (R.id.canclebutton);//Initialize handler, process the resulting runnable object handler = new handler ();//                 Click the button to execute worker thread Button.setonclicklistener (new Onclicklistener () {public void OnClick (View arg0) {                Thread thread = new Mythread ();            Thread.Start ();    }        });             } class Mythread extends thread{@Override public void Run () {//initialization of a Runnable object in worker Thread                        Runnable Runnable = new Runnable () {public void run () {//print out the thread executed by the Runnable method                System.out.println ("Current thread Name" +thread.currentthread (). GetName ()); }};//Post the RUNNABLE object Handler.post (runnable); }    }}

The final result is that this Runnable object executes in the main thread. With the post () method, we can directly make a Runnable object in the worker thread, and then write the code that updates the UI, directly using the Post method to update the UI.

Android's Handler

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.