Talk Android with it (Article 177 fifth back first: Android's Handler mechanism of four)

Tell me what you were Hello, everybody, let's say on a gyrus is an example of Android in the Handler mechanism, this time we went to this example. Gossip Hugh mentioned, words Reformed turn. Let's Talk Android now!

Tell me who, we analyzed the Handler class source code on a gyrus, Looper class analysis in this chapter back to the source code. It is implemented in the frameworks/base/core/java/android/os/Looper.javafile.

Let's look at its member variables, there are mainly two: one is used to store a message queue, further used to store a current thread, they are initialized in the constructor, detailed source code is as follows:

 private Looper(boolean quitAllowed) {
     mQueue = new MessageQueue(quitAllowed);  //消息队列在这里创建
     mThread = Thread.currentThread();
 }

Next we look at the focus of commonly used methods, first preparemethod, it is mainly used to make Looper initialization, the main content is to construct a Looper thread and objects and associate, whose source code is as follows:

 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));
 }

Then we analyze myLooper method, which is to return Looper main object for the current thread

 public static @Nullable Looper myLooper() {
     return sThreadLocal.get();
 }

The core of the method appearances, it is the loop method. Its main function is to run the news cycle, you will find essentially traverse the queue, the following is the source code after reading the source code, we ignore the many non-core operations:

 public static void loop() {
     final Looper me = myLooper();          //获取当前线程中的Looper
     final MessageQueue queue = me.mQueue;  //获取Looper中的消息队列
     for (;;) {                             //启动消息循环
         Message msg = queue.next();        //遍历消息队列中的每条消息
         msg.target.dispatchMessage(msg);   //通过dispatchMessage方法回调Handler中的handleMessage方法处理消息
     }
 }

Finally, the method is quit, which is used to exit the current loop Looper running message, its source code is following:

 public void quit() {
     mQueue.quit(false);
 }

Tell me, on Android Handler mechanism in case we described here, and there are any examples For, Let's hear next decomposition!

Published 528 original articles · won praise 131 · views 620 000 +

Guess you like

Origin blog.csdn.net/talk_8/article/details/105182955