Android logoff and handler message Summary

Source: Internet
Author: User

In Android development, in order to ensure that the UI thread can respond in a timely manner and avoid time-consuming operations, the interface may be suspended or even ANR. We usually put time-consuming operations such as downloading and querying in a separate thread. Then, update the result to the UI. The Android platform updates the interface in non-UI threads in the following ways:

Activity.runOnUiThread(Runnable)View.post(Runnable)AsyncTask<Params, Progress, Result>Handler.post(Runnable)

We use many of the following two methods, and asynctask is encapsulated based on handler. We can see that handler is a powerful tool for us to update the UI thread. Take a look at the commonly used handler constructor:

public Handler() {   this(null, false);}public Handler(Callback callback, boolean async) {    .....    mLooper = Looper.myLooper();    .....    mQueue = mLooper.mQueue;    mCallback = callback;    mAsynchronous = async;}

From the second method, we can see that creating a handler object mainly directs its final messagequeue mqueue scope to an object, and other scopes can be used by default. Mqueue comes from mloue = logoff. myloue (); check the implementation of the myloue () method:

public static Looper myLooper() {    return sThreadLocal.get();}// sThreadLocal.get() will return null unless you've called prepare().static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

It is time to explain threadlocal. threadlocal provides a copy of the variable value for each thread in Java and is a special thread binding mechanism in Java. Here, we only need to remember the following points: 1. The threadlocal value obtained in each thread is independent of the thread and is not associated with other threads. 2. To understand threadlocal, just remember the public void set (T) and Public t get () interfaces.
In fact, Android uses threadlocal to create a loose object for each UI thread. Each loose object has a message queue messagequeue. Each time a handler is declared, the main step is to bind the message queue of the current thread. Then, handler can be used to distribute the required operations to the message queue. Generally, logoff is executed at the beginning of each thread. prepare (); this is a private loe object created for the current thread. After that, handler can be declared. Generally, loler is executed at the end of each thread. loop (); previously, handler is bound to the Message Queue of the current thread. The loop () method listens to the message queue and performs operations. Therefore, this method is an infinite loop, the subsequent code will not be executed, so it will be executed at the end of the thread.
This mode is a bit like the producer and consumer mode in the university operating system. logoff is like a consumer, handler is like a producer. What's special is that there can only be one logoff consumer in one thread, the producer handler can have multiple. Next, let's take a look at the main code in logoff with the above knowledge:

public static void prepare() {    prepare(true);}private static void prepare(boolean quitAllowed) {    if (sThreadLocal.get() != null) {        throw new RuntimeException("Only one Looper may be created per thread");    }    sThreadLocal.set(new Looper(quitAllowed));}public static void loop() {    final Looper me = myLooper();    final MessageQueue queue = me.mQueue;    for (;;) {        Message msg = queue.next(); // might block        .....        msg.target.dispatchMessage(msg);    }}

In the program, if handler is involved in a sub-method and the current thread is not bound to a logoff (for example, handler may be required for an object allocated in a newly created thread ), an exception is thrown during running:

        if (mLooper == null) {            throw new RuntimeException(                "Can't create handler inside thread that has not called Looper.prepare()");        }

If lorule. Prepare () is executed only at the beginning of the thread, but lorule. Loop () is not executed, many operations will not be executed. :)

Finally, I would like to sum up the following: the handler. Post (runnable), which has been used for a long time, has not gone into depth to look at the principle. Android encapsulation is really good, and the stuff that involves updating the UI is enough. If there are some special needs for handlerthread, asynctask has been encapsulated for us. However, since the source code is made public, the implementation principle is better. O (distinct _ distinct) O ~~

Related Article

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.