Android Handler logoff and MessageQueue message mechanism Principle

Source: Internet
Author: User

Android Handler logoff and MessageQueue message mechanism Principle

Android message processing class:

Logoff, Handler, MessageQueue, Message, ThreadLocal, ThreadLocal. Values, and HandlerThread.

Logoff: the thread does not have a message loop by default. To create a message loop for a thread, call prepare (), and then call loop () the method enters the message loop (this means that the thread will keep repeating this method ). For example:
class LooperThread extends Thread {      public Handler mHandler;      public void run() {          Looper.prepare();          mHandler = new Handler() {              public void handleMessage(Message msg) {                  // process incoming messages here              }          };          Looper.loop();      }  }
So here you will surely think that the main thread of Android does not have prepare or loop, you can also create Handler to process message loops. This is because android has added a message loop for us when creating the main thread.
So how does a logoff manage a logoff corresponding to each thread?
public final class Looper {    // sThreadLocal.get() will return null unless you've called prepare().    static final ThreadLocal
 
   sThreadLocal = new ThreadLocal
  
   ();    private static Looper sMainLooper;  // guarded by Looper.class    final MessageQueue mQueue;    final Thread mThread;    private Printer mLogging;    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 prepareMainLooper() {        prepare(false);        synchronized (Looper.class) {            if (sMainLooper != null) {                throw new IllegalStateException("The main Looper has already been prepared.");            }            sMainLooper = myLooper();        }    }    public static Looper getMainLooper() {        synchronized (Looper.class) {            return sMainLooper;        }    }    public static void loop() {        final Looper me = myLooper();        if (me == null) {            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");        }        final MessageQueue queue = me.mQueue;        Binder.clearCallingIdentity();        final long ident = Binder.clearCallingIdentity();        for (;;) {            Message msg = queue.next(); // might block            if (msg == null) {                // No message indicates that the message queue is quitting.                return;            }            // This must be in a local variable, in case a UI event sets the logger            Printer logging = me.mLogging;            if (logging != null) {                logging.println(">>>>> Dispatching to " + msg.target + " " +                        msg.callback + ": " + msg.what);            }            msg.target.dispatchMessage(msg);            if (logging != null) {                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);            }            final long newIdent = Binder.clearCallingIdentity();            if (ident != newIdent) {                Log.wtf(TAG, "Thread identity changed from 0x"                        + Long.toHexString(ident) + " to 0x"                        + Long.toHexString(newIdent) + " while dispatching to "                        + msg.target.getClass().getName() + " "                        + msg.callback + " what=" + msg.what);            }            msg.recycle();        }    }    public static Looper myLooper() {        return sThreadLocal.get();    }
  
 
The above process is illustrated as follows: (prepare calls the get set Method of threadLocal)

Handler class: constructor: 1) Handler handler = new Handler (), which calls the public Handler (Callback callback, boolean async) method internally, assign the member variables mloue and mQueue of Handler to the looper object of the current thread and the corresponding message queue. If the current thread does not have looper, an exception is thrown. 2) Handler handle = new Handler (Looper loler). The public Handler (looper loler, Callback callback, boolean async) is called internally to pass the Looper object of the parameter to the mHandler object of handler, assign values to mQueue objects. This method can be used to create Handler for the main thread in other threads, for example, new Handler (lorule. getMainLooper ());
The sendMessage () method of handler internally assigns the handler object to the mTarget of the Message, and then calls mQueue to send the Message to the Message Queue of the thread. Message class: A Handler object mTarget is saved in the Message class.
Logoff's loop method, retrieves the Message, and then calls the dispatchMessage method of handler in the Message object. The dispatchMessage method is executed based on whether the callback is empty.
The flowchart is as follows:
HandlerThread is a thread class that allows you to create a simple message processing job.
Conclusion: 1) a Thread can be associated with a logoff at most. 2) One logoff has only one MessageQueue. 3) One handler can only be associated with one logoff. 4) A Message can be associated with only one handler with these four one-to-one relationships, so that the Message sending and processing are correct.











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.