Android的消息机制

Android的消息机制主要是指Handler的运行机制,Handler的运行需要底层的MessageQueue和Looper的支撑。
下面用一张图描述整个消息机制:


Handler

用来发送和接收消息。创建Handler对象时需要确保当前线程存在一个Looper,否则会抛出异常。Activity、Service在创建的时候已经帮我们创建好了Looper,所以我们不需要创建Looper。在其它线程如果需要使用Handler则需要创建Looper,如下所示:

Looper.prepare();
new Handler().obtainMessage(1).sendToTarget();
Looper.loop();

Looper.prepare()方法用来给当前线程设置新创建的Looper对象,Looper的构造方法里创建MessageQueue。Looper类部分源码如下:

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

/** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    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));
    }

Looper.loop()方法用来循环从消息队列获取消息,Looper部分代码如下:

/**
     * 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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

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

MessageQueue

消息队列在Android中指的是MessageQueue,它主要包括两个操作:插入和读取。读取操作本身会伴随着删除操作。插入对应的是enqueueMessage,读取对应的是next。MessageQueue是通过一个单链表的数据结构来维护消息队列。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. ANR异常 Application No Response:应用程序无响应。在主线程中,是不允许执行耗时的操...
    JackChen1024阅读 1,456评论 0 3
  • 前言 Handler是Android消息机制的上层接口,平时使用起来很方便,我们可以通过它把一个任务切换到Hand...
    eagleRock阅读 1,675评论 0 13
  • 前言: 提到Android消息机制大家应该都不陌生,在日常开发中都不可避免地要涉及到这方面的内容。从开发的角度来说...
    JiaYang627阅读 367评论 0 1
  • Android平台上,主要用到的通信机制有两种:Handler和Binder,前者用于进程内部的通信,后者主要用于...
    帝都De雾霾阅读 1,501评论 1 7
  • 你应该给你孩子什么? 育儿观念不同,对孩子的影响非常大。 平时,女儿都是我自己带,我妈有空就帮把手,所以我和我妈的...
    善良的吃瓜群众小央阅读 223评论 0 0