Android 的消息机制

前言

  这篇文章是我关于《Andorid开发艺术探索》一书中关于Android的消息机制一章的读书笔记,大部分内容从书中摘录,小部分内容是自己的理解。

正文

  Android的消息机制主要指Handler的运行机制,Handler的运行机制需要底层MessageQueue和Looper的支持。

一:关于Handler

1:Hanlder的创建
 /**
     * 默认无参数构造函数,也是我们常用的构造函数。
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     */
    public Handler() {
        this(null, false);
    }

    /**
     * 直接在构造函数中添加一个Handler.Callback,用于处理回调后的message;
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     */
    public Handler(Handler.Callback callback) {
        this(callback, false);
    }
    public Handler(boolean async) {
        this(null, async);
    }
    /**
     *接在构造函数中添加一个Handler.Callback,用于处理回调后的message;
     *   async 代表消息是不是异步的
     * @hide
     */
    public Handler(Handler.Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                        klass.getCanonicalName());
            }
        }

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

说明:这部分构造函数,前面的有参或者无参的构造函数都是指向最后一个构造函数,最后一个构造函数中参数:

  • Handler.Callback callback 代表直接添加消息回调callback,用来处理消息,好处是避免创建对象的引用。如下
Handler mHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
            }
        };
        new Handler(new Handler.Callback() {
//            ********等同于上面的处理消息方法,不常用,这里需要记住,后面还会用到(**1**)
            @Override
            public boolean handleMessage(Message msg) {
                return false;
            }
        });
  • async 代表消息是不是异步的,一般都是false,代表同步(个人理解,不合适的地方请赐教)
    /**
     * 手动添加一个looper(不能是空),替代线程中默认的looper
     */
    public Handler(Looper looper) {
        this(looper, null, false);
    }
    /**
     * U手动添加一个looper(不能是空),替代线程中默认的looper
     * 直接在构造函数中添加一个Handler.Callback,用于处理回调后的message;
     */
    public Handler(Looper looper, Handler.Callback callback) {
        this(looper, callback, false);
    }

    /**
     *手动添加looper代替线程默认的looper,其他都是赋值过程,不赘述
     *
     * @hide
     */
    public Handler(Looper looper, Handler.Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

说明:到这里关于Handler的创建结束了,简单来说就是需要手动添加Looper和不需要手动添加Looper最后指向不同。另外几个构造函数,看到最多的,就是Handler,必须有当前线程对应的Looper来构造消息循环系统,至于Looper是何方神圣,后面会讲到。

Handler 发送消息部分

Handler发送消息方法, 主要分两种,分别是handler.post(Runable r)和handler.send(Message m)两种。

  • 关于handler.post(Runable r)系列;
 public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

public final boolean postAtTime(Runnable r, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r), uptimeMillis);
    }

public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
    }

public final boolean postDelayed(Runnable r, long delayMillis)
    {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }
public final boolean postAtFrontOfQueue(Runnable r)
    {
        return sendMessageAtFrontOfQueue(getPostMessage(r));
    }

这两个方法作用都是构造一个Message对象,m.callback = r(**2**)这里需要记住,后面回提到;
private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

    private static Message getPostMessage(Runnable r, Object token) {
        Message m = Message.obtain();
        m.obj = token;
        m.callback = r;
        return m;
    }

可以看到,handler.post(Runable r)系统方法,最终都指向了handler.send(Message m) 系列了,那么我们直接看看handler.send(Message m)到底是啥。

  • 关于handler.send(Messge m ) 系列方法:
  /**
     * 参数发送消息的对象
     *返回如果消息成功放进MessageQueue中,返回true,否则返回false(返回false,通常是因为消息队列正在退出)
     */
    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

    /**
     * Sends a Message containing only the what value.
     *
     参数发送消息的对象(仅仅包含what 值)
     *返回如果消息成功放进MessageQueue中,返回true,否则返回false(返回false,通常是因为消息队列正在退出)
     */
    public final boolean sendEmptyMessage(int what)
    {
        return sendEmptyMessageDelayed(what, 0);
    }

    /**
     * Sends a Message containing only the what value, to be delivered
     * after the specified amount of time elapses.
     * 参数发送消息的对象(仅仅包含what 值)  发送消息的动作被延迟
     *      *返回如果消息成功放进MessageQueue中,返回true,否则返回false(返回false,通常是因为消息队列正在退出)
     */
    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }

    /**
     * Sends a Message containing only the what value, to be delivered
     * at a specific time.
     * 参数发送消息的对象(仅仅包含what 值)  指定时间触发发送消息的动作
     *      *返回如果消息成功放进MessageQueue中,返回true,否则返回false(返回false,通常是因为消息队列正在退出)
     */

    public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageAtTime(msg, uptimeMillis);
    }

    /**
     * Enqueue a message into the message queue after all pending messages
     * before (current time + delayMillis). You will receive it in
     * {@link #handleMessage}, in the thread attached to this handler.
     *
     * @return Returns true if the message was successfully placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.  Note that a
     *         result of true does not mean the message will be processed -- if
     *         the looper is quit before the delivery time of the message
     *         occurs then the message will be dropped.
     *         * 参数发送消息的对象  延迟多少时间触发发送消息的动作
     *      *      *返回如果消息成功放进MessageQueue中,返回true,否则返回false(返回false,通常是因为消息队列正在退出)
     *      
     *      *true的结果并不意味着消息将被处理--如果在邮件的传递时间之前退出循环器发生,则消息将被删除。
     *
     * *
     *
     * *
     */
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

    /**
     * Enqueue a message into the message queue after all pending messages
     * before the absolute time (in milliseconds) uptimeMillis.
     * The time-base is {@link android.os.SystemClock#uptimeMillis}.
     * Time spent in deep sleep will add an additional delay to execution.
     * You will receive it in {@link #handleMessage}, in the thread attached
     * to this handler.
     *
     * @param uptimeMillis The absolute time at which the message should be
     *         delivered, using the
     *         {@link android.os.SystemClock#uptimeMillis} time-base.
     *
     * @return Returns true if the message was successfully placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.  Note that a
     *         result of true does not mean the message will be processed -- if
     *         the looper is quit before the delivery time of the message
     *         occurs then the message will be dropped.
     */
    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        return enqueueMessage(queue, msg, uptimeMillis);
    }

可以看到所有send()方法最后都指向了sendMessageAtTime(Message msg, long uptimeMillis),这里面逻辑也很简单,首先获取MessageQueue对象,如何为空直接返回false,否则调用enqueueMessage(queue, msg, uptimeMillis)方法

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

说明这里的msg.target就是指向handler对象,mAsynchronous等同于handler构造函数中参数async。
等同于直接调用了queue.enqueueMessage(msg, uptimeMillis)方法跟进去看看:

boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

说句实话,这部分代码我也看不懂了,书中说,这里是一些算法,整个方法的作用就是将message放入messageQueue中。
到这里关于handler发送消息的方法基本上结束了,简单来说就是:
handler.post(Runnale r)-------》handler.send(message s)------》sendMessageAtTime(Message msg, long uptimeMillis)-----》
enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) -------》queue.enqueueMessage(msg, uptimeMillis);
到这里我还有一个疑问,关于消息的延迟操纵,延迟的是放入MessageQueue()动作吗?还有就是这种延迟,会影响后面Looper处理消息时间吗?说messageQueue是一种先进先出队列,这种说法严谨吗?

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);
        }
    }
private static void handleCallback(Message message) {
        message.callback.run();
    }
/**
     * Callback interface you can use when instantiating a Handler to avoid
     * having to implement your own subclass of Handler.
     *
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public interface Callback {
        public boolean handleMessage(Message msg);
    }

**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }


说明dispatchMessage(Message msg)方法中,先判断msg.callback(对应(2)处,也就是msg.callback等同于handler,post(Runable r),中的Runable对象)是不是null,不是null就调用handleCallback(Message message),然后调用message.callback.run(),这个方法对应这里:

mHandler.post(new Runnable() {
            @Override
            public void run() {
                
            }
        });

如果是null,就判断mCallback(对应(1)处,也就是Handler构造方法传进来的Handler.Callback对象)是不是null,不是null,调用handleMessage(Message msg),对应这里:

new Handler(new Handler.Callback() {
//            ********等同于上面的处理消息方法,不常用,这里需要记住,后面还会用到
            @Override
            public boolean handleMessage(Message msg) {
                return false;
            }
        });

最后才调用了handleMessage(Message msg),这个空实现方法,处理逻辑需要自己处理,即:

Handler mHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
            }
        };

到这里关于Handler基本结束了,Handler的构造函数中,注释写的最多的一句话就是Hanlder的每个对象都必须有相应线程的Looper,否则会报异常。下面就说说这个Looper。


二 关于MessageQueue

messageQueue本质上是一个单链表的数据结构来维护消息队列,因为单链表的数据结构在插入和删除上比较有优势.

主要方法有:
  • enqueueMessage()存放消息,单链表的插入,这个方法就是handler,.send()方法最终调用的方法源码往上找;
  • next()取消消息并删除,是一个无限循环的方法,如果没有消息那么next()方法会一直阻塞在这里,当有新消息的时候,next()方法会返回这条消息并将其从链表中移除
Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

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

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }
  • quit()方法
void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            nativeWake(mPtr);
        }
    }

三 关于Looper

Handler创建的时候会采用当前线程的Looper来构造消息循环系统。
Looper是消息循环的角色,具体来说就是会不停地从messageQueue中查看是否有新消息。有消息就处理,没消息就会一直阻塞在那里。

  • Looper.prepare(); 创建Looper对象;

static final ThreadLocal sThreadLocal = new ThreadLocal();
 /** 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));
    }
private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }


关于ThreadLocal的内容会面会详细介绍,这里只需要知道:ThreadLocal是用于存放Looper的一个容器。另外
Hander内部也是使用ThreadLocal获取当前线程的Looper。ThreadLocal可以在不同的线程中互不干扰地存储并提供数据,通过ThreadLocal可以轻松的获取每个线程的Looper

  • Looper.prepareMainLooper()(本质上调用的Looper.prepare());创建主线程的Looper;
 /**
     * Initialize the current thread as a looper, marking it as an
     * application's main looper. The main looper for your application
     * is created by the Android environment, so you should never need
     * to call this function yourself.  See also: {@link #prepare()}
     */
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

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

可以看到最终还是调用了 prepare(false);,但是这里需要提到一点就是从参数可以看出,因为 prepareMainLooper()是创建主线程的Looper的,默认不允许暂停或者终止的(主线程的消息循环模型涉及到管理四大组件的启动暂停,所以系统默认不让终止)

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

Looper.loop()方法是一个死循环,唯一能跳出死循环的条件就是messageQueue的next()方法返回null

  • Looper.getMainLooper(); 获取主线程的Looper;
/**
     * Returns the application's main looper, which lives in the main thread of the application.
     */
    public static Looper getMainLooper() {
        synchronized (Looper.class) {
            return sMainLooper;
        }
    }
  • Looper.quit();直接退出looper;
/**
     * Quits the looper.
     * 

* Causes the {@link #loop} method to terminate without processing any * more messages in the message queue. *

* Any attempt to post messages to the queue after the looper is asked to quit will fail. * For example, the {@link Handler#sendMessage(Message)} method will return false. *

* Using this method may be unsafe because some messages may not be delivered * before the looper terminates. Consider using {@link #quitSafely} instead to ensure * that all pending work is completed in an orderly manner. *

* * @see #quitSafely */ public void quit() { mQueue.quit(false); }
  • Looper.quitSafely(); 只是设定一个标记,等消息队列中消息处理完毕后才安全退出。
**
     * Quits the looper safely.
     * 

* Causes the {@link #loop} method to terminate as soon as all remaining messages * in the message queue that are already due to be delivered have been handled. * However pending delayed messages with due times in the future will not be * delivered before the loop terminates. *

* Any attempt to post messages to the queue after the looper is asked to quit will fail. * For example, the {@link Handler#sendMessage(Message)} method will return false. *

*/ public void quitSafely() { mQueue.quit(true); }

当Looper的quit()方法被调用的时候,Looper就会调用MessageQueue的quit()或者quitSafely()方法,然后next()方法就会返回null.因为next()方法是一个阻塞操作,没有消息就一直阻塞,导致loop()方法也阻塞在那里。


小结

Android 消息模型的Hanlder,Looper,MessageQueue都介绍完了,这里做一个简单总结:

  • Handler 负责发送消息和处理消息,任何线程创建Hanlder,必须有该线程独有的Looper与之对应;
  • MessageQueue 单链表的数据结构,存放消息;
  • Looper 负责轮询分发处理MessageQueue中的消息;

整个消息流转大致是这样的:

  • Loop.prepare(),创建线程独有的Looper,然后创建Hanlder对象mHanlder;
  • Looper.loop(),开启轮询循环,有消息处理消息,没有消息messageQueue.next()=null,阻塞状态;
  • mHanlder.send(Message s)-------》messageQueue.enqueueMessage() 将消息放入MessageQueue中;
  • messageQueue.next不是null,这时候Looper.loop()方法就会调用msg.target.dispatchMessage(msg);
  • 前面说过msg.target对应mHanlder,msg.target.dispatchMessage(msg)也就是mHanlder.dispatchMessage(msg),但是这时候消息处理逻辑,是在looper中执行的,也就是在这里达到切换线程的目的

补充

Handler的主要作用就是:将某一个任务切换到某个指定的线程中区执行(ViewRootImpl的checkThread()检验操作UI的线程是不是主线程),提供Handler的主要原因就是为了解决在子线程中无法访问UI的矛盾。

1#系统为什么不允许在子线程中访问UI呢?

这是因为Android的UI控件不是线程安全的,如果多线程中并发访问可能会导致UI控件处于不可以预期的状态。

2#那为什么不会UI控件的访问加上锁机制呢?
  • 加上锁机制会让UI访问逻辑变得复杂;
  • 加上锁机制后悔降低UI的访问效率,因为锁机制会阻塞某些线程的执行。
3#ThreadLocal的工作原理:

ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储之后,只有在指定的线程中才能获取到存储的数据,其他线程则无法获取到。
一般来说,当某些数据是以线程为作用域并且不同线程具有不同的数据副本的时候,可以考虑使用ThreadLocal.比如所Handler来说,它需要获取当前线程的Looper,很显然Looper的作用域就是线程并且不同线程具有不同的Looper.
ThreadLocal工作原理就是:根据不同的线程参数分别创建不同的数据存储容器对象,然后再根据固定的算法获取存储对象指定的数据。
从ThreadLocal的set和get方法可以看出,他们所操作的对象都是当前线程的localValues的table数组,因此在不同线程中访问同一个Threadlocal的set和get方法,他们对ThreadLocal所做的读写操作仅限于各自的线程的内部。

4 主线程的消息循环模型:

Android 的主线程是ActivityThread,主线程的入口方法是main()方法,main()方法中系统会通过Loop.prepareMainLooper()来创建主线程的Looper以及MessageQueue,并通过Looper.loop()开发消息循环。
ActivityThread还需要一个Hanlder,就是ActivityThread.H,它内部定义了一组消息类型,主要包含四大组件的启动和停止等过程。
ActivityThread通过ApplicationThread和AMS进行进程间消息通信,AMS以进程间的消息通信完成ActivityThread的请求后会回调ApplicationThread中的Binder方法,然后ApplicationThread会向H发送消息,H接到消息后会将ApplicationThread中的逻辑切换到ActivityThread中执行,即切换到主线程中去执行。

你可能感兴趣的:(Android 的消息机制)