Android源码解析Handler系列第(三)篇---深入了解Android的消息机制

转载请注明文章出处LooperJing

Android的消息机制我觉得是每一个弄Android开发的人都要弄懂得问题,也有很多人对它进行研究,Android的消息机制的重要性不强调,但是觉得自己对Android的消息机制了解不深刻,所以决定深入源码,写下三篇博客以记之。因为Message全局池和ThreadLocal对Android的消息机制理解很重要,附上前两篇的博客地址。
Android源码解析Handler系列第(一)篇 --- Message全局池
Android源码解析Handler系列第(二)篇 --- ThreadLocal详解

先来一张图感受一下,下面这张图基本说明了Android的消息机制的工作流程。


Android的消息机制

不看别的,主要涉及的类有Thread,Looper,MessageQueue,Handler,其实还有一个ThreadLocal,这些类都是整套消息机制中很关键的类,下面我们正式分析这套机制是怎么运行的。

要分析这套机制是怎么运行的,要首先从应用程序的入口说起,Android应用程序的入口是ActivityThread类的main方法。下面是main方法中的相关代码。

 public static void main(String[] args) {
    

        Process.setArgV0("<pre-initialized>");

        //创建UI线程所需要的Looper,Looper有何用,后面再说
        Looper.prepareMainLooper();

        //这里最终启动应用程序
        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
        //执行消息循环
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

注意到,入口函数的最后一行代码是Looper调用了静态方法Looper. loop(),而这个loop是死循环,按照正常的理解,在主线程中执行死循环,那么就不能做其他任务了,比如按钮事件的触发,动画的播放等。但是反过来想一想,如果这不是死循环,那么最后一行代码执行完,应用程序不就跑完了嘛。并且这行代码也只能放在main的最后一句,如果放在前面,后面的程序就没有办法进行了。

好滴, Looper.loop()是执行消息循环,去这里看个究竟。

/**
   * Run the message queue in this thread. Be sure to call
   * {@link #quit()} to end the loop.
   */
  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;

      // Make sure the identity of this thread is that of the local process,
      // and keep track of what that identity token actually is.
      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);
          }

          // Make sure that during the course of dispatching the
          // identity of the thread wasn't corrupted.
          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.recycleUnchecked();
      }
  }

代码比较长,但是真的比较容易理解的,第一句执行final Looper me = myLooper()获取一个Looper对象,怎么获取的呢?在myLooper中涉及到了ThreadLocal,对ThreadLocal不了解的,看我的第二篇博客。


  /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

如果sThreadLocal.get()返回了NULl,那么程序就会 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); ,尼玛,如果主线程在这都抛了异常,那还玩毛线,所以必然有sThreadLocal.set()。回到刚才,在执行消息循环Looper.loop之前,有一句关键的代码, Looper.prepareMainLooper(),这句话可以创建UI线程所需要的Looper,跟踪进去。

 public static void prepareMainLooper() {
        //代码在下面
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
          //从sThreadLocal中获取Looper,系统默认给我们创建了sMainLooper
            sMainLooper = myLooper();
        }
    }

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

在sThreadLocal.get() 为NULL的情况下,直接以饿汉式的方式new了一个Looper, 调用sThreadLocal的set方法,这一步,通过sThreadLocal,其实是将Looper与当前线程(UI线程)做了关联, 也就是说上面创建的Looper对象me只能被主线程所访问,其他线程访问不了!!!,这就是ThreadLocal的厉害之处。Looper我们称之是消息循环器,就是不断的把消息从消息队列中取出来,看一个创建Looper干了什么。

private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

主要是初始化了一个消息队列,原来消息队列是Looper里面的成员,记住了!!!,还保留了当前线程,有了mThread,我们就可以知道这个Looper是哪一个线程的Looper。Looper的成员非常少,就几个,看下面。

    // sThreadLocal.get() will return null unless you've called prepare().
     static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
   
     private static Looper sMainLooper;  // guarded by Looper.class

     final MessageQueue mQueue;
  
     final Thread mThread;

OK,在ActivityThread中的Looper.loop()这个死循环启动之前,需要执行 Looper.prepareMainLooper(),这个方法执行以后,我们知道发生了以下几件事情。

  • 1、以饿汉式的方式创建了主线程的Looper对象
  • 2、用sThreadLocal将主线程与这个Looper对象关联起来
  • 3、sThreadLocal.get一个Looper对象,赋值给sMainLooper。

继续看Looper.loop()里面,第二句关键代码是final MessageQueue queue = me.mQueue;即获取Looper中的消息队列,之后是一个死循环,对消息队列里面的消息进行遍历,在这里我们先留一个问题 消息是怎么存到消息队列里面去的?

 for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            msg.target.dispatchMessage(msg);

            msg.recycleUnchecked();
        }

在这个死循环中遍历,通过queue.next()取出消息。

  Message next() {
        
        for (;;) {
          
            //这句代码水比较深,先跳过
            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

            } 
        }
    }

在同步synchronized中,这一大段代码也就是写消息何时出队列的事情。

if (now < msg.when) {
         // Next message is not ready.  Set a timeout to wake up when it is ready.
            nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
        }

nextPollTimeoutMillis表示消息出队列的时间,如果现在的时间now比Message要执行的时间msg.when要小,就减去现在的时间,计算一个新的时间给nextPollTimeoutMillis。如果消息的执行时间已经到了,那么就取出这个消息返回并调用msg.markInUse(),把消息的状态赋值为使用之中。

OK,在上面那个for循环中,消息是取到之后,就要进行消息的分发了,消息的分发也是有一套顺序的。调用 msg.target.dispatchMessage(msg),进行消息的分发,不知道target是什么的(是Handler对象,标识这个消息被谁处理),去看我的第一篇博客。

    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

这里具体可以看我第一篇博客中****Message的处理顺序****章节,可以知道Message是怎么进行分发的,从消息的分发可以看到,如果没有Runnable的类型的消息callback以及没有Callback类型的回调mCallback,那么就会回调Handler的handleMessge。

   private Handler  handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
           dosomething();
        }
    };

上面试我们常常写的代码,走到这,相信你已经知道我们常写的那个套路是怎么来的了。在Looper.looper中还有最后一句代码 msg.recycleUnchecked();这个就不用讲了,主要做消息的回收操作,这里消息会进入消息的全局池中。

上面留下了一个问题****消息是怎么存到消息队列里面去的?****现在来分析分析,这个从我们发送消息(handler.sendMessage())来入手,经过查看源码,sendMessage中会掉一系列方法,最终走到enqueueMessage中。如下图。


对于enqueueMessage中代码就不分析了,现在我们知道消息是怎么进入消息队列的,又是怎么被Looper给取走,交给Handler去处理的了,整个消息机制基本就弄清楚了。其实,严格来说,消息可以分为系统消息和我们自定义的消息,自定义的消息就是发送一个Message,然后在handlerMessage中进行处理,那么系统的消息呢,比如四大组件的生命周期回掉是系统消息,跨进程通信也是系统消息,应用程序退出还是一个系统消息。这些消息在哪里?谁来处理呢?在ActivityThread中有一个成员final H mH = new H();这个mH就是来处理系统消息的。

 private class H extends Handler {
        public static final int LAUNCH_ACTIVITY         = 100;
        //...
        public static final int ENTER_ANIMATION_COMPLETE = 149;

        String codeToString(int code) {
            if (DEBUG_MESSAGES) {
                switch (code) {
                    case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
                      //...
                    case ENTER_ANIMATION_COMPLETE: return "ENTER_ANIMATION_COMPLETE";
                }
            }
            return Integer.toString(code);
        }
        public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
                  //...
                case LAUNCH_ACTIVITY: {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                    final ActivityClientRecord r = (ActivityClientRecord) msg.obj;

                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    handleLaunchActivity(r, null);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } break;
            
                case PAUSE_ACTIVITY:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
                    handlePauseActivity((IBinder)msg.obj, false, (msg.arg1&1) != 0, msg.arg2,
                            (msg.arg1&2) != 0);
                    maybeSnapshot();
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
                case PAUSE_ACTIVITY_FINISHING:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
                    handlePauseActivity((IBinder)msg.obj, true, (msg.arg1&1) != 0, msg.arg2,
                            (msg.arg1&1) != 0);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
             
                case HIDE_WINDOW:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityHideWindow");
                    handleWindowVisibility((IBinder)msg.obj, false);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
                case RESUME_ACTIVITY:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
                    handleResumeActivity((IBinder) msg.obj, true, msg.arg1 != 0, true);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
              
                case DESTROY_ACTIVITY:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityDestroy");
                    handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
                            msg.arg2, false);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
                case CREATE_SERVICE:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceCreate");
                    handleCreateService((CreateServiceData)msg.obj);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
                case BIND_SERVICE:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
                    handleBindService((BindServiceData)msg.obj);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
                case UNBIND_SERVICE:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceUnbind");
                    handleUnbindService((BindServiceData)msg.obj);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
                case SERVICE_ARGS:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStart");
                    handleServiceArgs((ServiceArgsData)msg.obj);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
                case STOP_SERVICE:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");
                    handleStopService((IBinder)msg.obj);
                    maybeSnapshot();
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
             
                case SUICIDE:
                    Process.killProcess(Process.myPid());
                    break;
              //...
            }
            if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
        }
    }

看到了吧,如果要退出应用程序,需要发送一个SUICIDE消息,绑定服务需要发送一个BIND_SERVICE消息等等。

最后总结一个Android消息机制涉及到的类以及类的重要方法,在整个机制中它们扮演着不同的角色也承担着各自的不同责任。

  • Thread
    负责业务逻辑的实施。
    线程中的操作是由各自的业务逻辑所决定的,视具体情况进行。

  • Handler
    负责发送消息和处理消息。
    通常的做法是在主线程中建立Handler并利用它在子线程中向主线程发送消息,在主线程接收到消息后会对其进行处理

  • MessageQueue
    负责保存消息。
    Handler发出的消息均会被保存到消息队列MessageQueue中,系统会根据Message距离触发时间的长短决定该消息在队列中位置。在队列中的消息会依次出队得到相应的处理。

  • Looper
    负责轮询消息队列。
    Looper使用其loop()方法一直轮询消息队列,并在消息出队时将其派发至对应的Handler.

  • ThreadLocal
    将线程和Looper相关联

Please accept mybest wishes for your happiness and success

参考资料:http://blog.csdn.net/lfdfhl/article/details/53332936

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容