Android Curiosity baby _09_handler Looper Message

Source: Internet
Author: User
Tags message queue ticket

Finding out what you're talking about is UI-related, and this is about Android's very important point of knowledge: Handler Looper Message.

Talk less and go straight to the chase.


(1) Meaning of existence:

I've been Handler Looper. Message These classes are a few of the tools that can be used together, in particular because they are provided by the system and are used by the system itself.


Since it is a tool class, what is its function?

A: A unique message queue is established on the current thread, and handler can be used to add messages to the message queue,Looper continuously removes the message from the message queue and forwards the handler that sent the message. Feeling is handler send message, and then back to handler, very bored right.


So what's the effect of doing such a boring thing?

A: Solve multi-threaded concurrency problems.


First, what is a multithreaded concurrency problem:

Multiple threads operate on the same block of memory at the same time, because the order in which the threads are executed cannot be determined, resulting in unpredictable results.


The new year is coming, give a classic chestnut:

Two Windows A and b for selling train tickets, when there are 1 train tickets, A and b at the same time to the people to buy tickets, aand b a check, there are 1 tickets left, so the tickets sold to these two people, the result may be two people have received a ticket, but the total number of votes more than one, and the remaining votes of 1 This does not conform to the actual logic of the number


Here's how it's solved:

The general solution to multithreading concurrency problem is to add various types of locks, the role of these locks is to ensure that at some point, only one thread can make access to modify, but Android does not do so.


Android is a single-threaded model, what is a single-threaded model?

A: The single-threaded model does not mean that there is only one thread (not in Android, at least), but that the variables within that thread allow access only to themselves and not to other threads. to solve the problem of multithreading concurrency, using the above train ticket example is a and B can sell tickets, but only a can be issued tickets, b must go to a there to get tickets.


Specifically on the Android system, the UI control is accessible only on the UI thread (the main thread) and not directly on other threads.


(How is the UI related, I go)


This solves the problem of multithreading concurrency, preventing multiple threads from modifying a UI control at the same time, causing confusion in the state. But it raises another question as to what to do when other threads need to access the control, such as I have a download thread to update the download progress to ProgressBar?

(This example is not good, ProgressBar do a special processing, can be directly in the non-UI thread operation, is actually using the handler, just automatically help us do it, we understand the meaning of the line)

A: So it produced the protagonist of our day,Handler Looper message! When another thread wants to access the modified UI control, it cannot be accessed directly, but it can send a message to the UI thread through handler and let the UI thread help it modify it.


Here's a simulation of what happens when a Handler Looper message has multiple threads that want to modify a UI control at the same time:

First, thread A wants to modify the control K, so it sends a message to the UI thread's message queue via handler, which is added to the message queue, and thread B does the same thing. At this point two messages that modify the control k are added to the message queue and then looper the message queue without pausing to process it, but looper only takes one message at a time, so the two messages are not processed concurrently.


It says that the role of Handler Looper message is to solve the problem of multithreading concurrency is not correct, specifically, their role is to let the UI thread can communicate with other threads securely.


Train tickets under Handler Looper message:

Or two people to A and B two window to buy tickets, because only a can be issued tickets, so B to a said: "I need a ticket here" (equivalent to send a message with handler in the queue). at this point a also said I also need a ticket (add a message), then another person C (Looper) from the message queue to take out the message to a processing (first out that depends on the message first queue), a processing the first message when there are 1 tickets, so a out of a ticket, When processing the second message, there was no ticket, so it said with schadenfreude: "There is no ticket, that cool to stay."

Because a is in the process, so two messages will not be processed at the same time, there will not be two times to check that there is a ticket left.


(2) Internal mechanism:

First, then look at the code:


(Note starting from handler)


HD Feed Code:

(1) Establishment of Looper and MessageQueue

The Looper and the message mentioned above have been used by the class systems themselves, so when was it used?

A: When the app is open, create the first activity.


Specific analysis:

Starting with the simplest helloworld, we are accustomed to the main method as the entrance to the program. Remember that the book said there must be a Mian method to call a Java program, but we have not written the main method of Android application, then our program entrance is where?

Actually there is the main method, but this class is provided by the system, not what we write, it is activitythread (note that although the end of thread, but Activitythread is not inherited from the thread class, in fact, it does not inherit any class ), here is the main method of Activitythread:

  public static final void main (string[] args) {        looper.preparemainlooper ();//Prepare to Looper        //...        //Do some things that need to be done when the app starts        //...        Looper.loop ()//start cycle        //...        //Do some things that need to be done when the application is destroyed        //...  }
What is the preparation for Looper?

A: First create a new looper for the current thread:

Preparemainlooper ()->prepare (Boolean)->new Looper (Boolean)

Then a new MessageQueue is created in the Looper construction method :

    Private Looper (Boolean quitallowed) {        mqueue = new MessageQueue (quitallowed);        Mthread = Thread.CurrentThread ();    }


The difference between the (Preparemainlooper () and prepare () methods is that preparemainlooper () New looper is not manually terminated )


here is also a knowledge point is Looper is stored in the threadlocal, simple point is that threadlocal can ensure that each thread has its own exclusive looper and MessageQueue. Details on the Internet to check.


Start message loop after Setup is complete:

    public static void Loop () {        final Looper me = Mylooper ();//Get yourself        final MessageQueue queue = me.mqueue;//Get Message Queue 
   //Start message loop for        (;;) {            Message msg = Queue.next ();            if (msg = = null) {                return;            }            Message is not empty, send the message back to Handler            Msg.target.dispatchMessage (msg);        }    }


There are 3 ways to do this when the message is sent back, and DispatchMessage is to notify these 3 ways:

    public void DispatchMessage (Message msg) {        if (msg.callback! = null) {        ///First, set callback for Message (callback            ) Handlecallback (msg);        } else {        //second, set callback for handler (this is preferred by the individual)            if (mcallback! = null) {                if (Mcallback.handlemessage (msg)) {                    return;                }            }            Third, rewrite handler's Handlemessage method            handlemessage (msg);}    }


(2) General usage of handler:

It says I prefer the second way, so I usually do this new handler:

Handler Mhandler = new Handler (new Handler.callback () {@Overridepublic Boolean handlemessage (Message msg) {//DoSomething return false;}});


And then you can start calling Mhandler.sendmessage (msg) to add a message to Message Queuing:

Each SendMessage method takes several overloads and finally calls the Sendmessageattime method, andSendmessageattime calls the Enqueuemessage method:

    Private Boolean enqueuemessage (MessageQueue queue, Message msg, long Uptimemillis) {        // Note that the target of the message is set to handler itself    //so that the message can be found on the way home        msg.target = this;        if (masynchronous) {            msg.setasynchronous (true);        }        MessageQueue's Enqueuemessage method is a queue operation, where it is no longer in depth        return Queue.enqueuemessage (msg, uptimemillis);    }


So my handler adds a message to MessageQueue, and when Looper gets the message back to my Mhandler, the callback I set will be executed.


(3) Just say the word.


<1>looper and MessageQueue are one by one corresponding,MessageQueue are created in the Looper constructor method.


<2> each thread can have at most one looper and its corresponding Messagequeue,ui thread (the main thread) of Looper and MessageQueue created by the system, without Looper and MessageQueue lines thread Create handler send messages will produce an exception (Message Queuing is not where you want to send it).


<3> Note that messages sent by handler are message queues that are sent to that thread. You can specify looper at new, and the message will be sent to the looper corresponding MessageQueue. If Looper is not specified, the looper of the current thread is assigned to handler (assuming that the current thread has Looper), and the looper of the current thread is the credit for threadlocal. Once again, interested in threadlocal please check online.


Seeking comment and advice

Android Curiosity baby _09_handler Looper Message

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.