Android开发进阶—Android的消息机制

1.什么是Android的消息机制

       提到Android的消息机制大家应该都不会陌生,在日常的开发中不可避免的要涉及到这方面的内容。在开发的角度上来看,Android的消息机制主要是指Handler的运行机制,Handler在运行的过程中需要底层的MessageQueue和Looper的支持,MessageQueue为消息队列,但是它的内部储存结构并不是队列而是链表的结构,毕竟对于MessageQueue这种要频繁的进行插入和删除操作的结构来说,使用链表会有一定的优势,而Looper中文翻译为循环,在这里可以理解为消息的循环。由于MessageQueue只是一个消息的储存单元,而不能去处理消息,Looper的出现就正好填补了这个空缺,在消息机制的工作过程中Looper会以无限循环的形式去在MessageQueue中查找是否有新的消息,如果有新的消息就把它交给Handler去处理,如果没有新的消息就阻塞。总之Handler、MessageQueue和Looper的三者关系可以概括为,Looper中维护着一个MessageQueue, Handler发送的消息会进入到MessageQueue也就是消息队列中,同时Looper会不断的轮询MessageQueue中是否有消息,如果存在消息,Looper将消息从MessageQueue中取出,交给Handler处理。


       以上就是Android消息机制的原理图

2.MessageQueue的工作原理

       在MessageQueue中最重要的两个操作就是插入和读取,这两个操作分别对应的方法为enqueueMessage和next,其中enqueueMessage的作用就是往消息队列中插入一条消息,而next的作用则是从消息队列中读取出一条消息并将其从消息队列中移除。

       enqueueMessage的源码如下

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;
    }
       从enqueueMessage的源代码中可以看出,首先会检查msg的合法性,如果不合法则抛出异常,其次可以看出enqueueMessage中通过链表的数据结构来维护消息列表,把从外部传递进来的消息(参数msg)插入到消息列表中。

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

       从next的源代码中可以看出,在next()方法中启动一个无限循环,如果消息队列中有消息时,next()方法会返回这条消息并且将这条消息从MessageQueue中删除,如果消息队列中没有消息,那么next()方法将会一直阻塞在这里。

3.Looper的工作原理

      Looper在Android的消息机制中扮演着消息循环的角色,具体来说它会不停的从MessageQueue中查看是否有新的消息,如果有新的消息就传递给Handler进行处理,否则就会一直阻塞在那里。我们都知道Handler的工作需要Looper,在没有Looper的线程中使用Handler就会报错,其实可以通过Looper.prepare()为当前线程创建一个Looper,紧接着通过Looper.loop()方法来开启消息队列的循环。

       Looper.prepare()的源码如下

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));
    }
       通过源代码可以看出,prepare()方法会先通过Looper的构造方法创建Looper的一个对象,并把这个对象保存在ThreadLocal中,那么ThreadLocal又是什么呢?我们只需要知道ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,在数据存储以后只有在指定的线程中可以获取到存储的数据,而在其它的线程中无法获取。

      Looper构造方法的源码如下

private Looper(boolean quitAllowed){
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
}
       通过源代码可以看出,在Looper创建对象的同时会创建一个MessageQueue的对象mQueue。

       Looper.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();
        }
    }
       loop()是Looper中最重要的一个方法,因为只有调用了loop以后,消息循环才会正在的启用。通过源代码可以看出,loop()方法是一个死循环,唯一跳出循环的方式是MessageQueue的next()方法返回了null。在这个死循环中会不断的通过MessageQueue的next()方法取出消息,当取出的消息不为空时则执行msg.target.dispatchMessage(msg)触发Handler处理消息,这样就成功的将代码逻辑切换到指定的线程中去执行了。

       由上文对MessageQueue的介绍中可以知道,如果消息列表中没有消息,next()方法则会阻塞,因此loop()方法当消息列表中没有消息时是处于阻塞状态。当Looper的quit方法被调用时,Looper就会调用MessageQueue的quit或者quitSafely方法来通知消息队列的退出,当消息队列被标记为退出状态时,它的next()方法就会返回null。

4.Handler的工作原理

       Handler的工作主要包含消息的发送和接收过程,消息的发送主要是通过post的一系列方法和send一系列方法来实现,而post的一系列方法最终也是通过send的一系列方法来实现的,消息的接收是通过在主线程中创建Handler对象并重写handleMessage()方法,在该方法中接收并处理消息。

       创建Handler对象并重写handleMessage()方法

Handler mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
            }
        };
       在子线程通过mHandler发送消息

mHandler.sendMessage(msg);
       Handler的构造方法的源码如下

public Handler() {
        this(null, false);
    }

 public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> 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对象的时候我们使用的是无参数的构造方法,在无参的构造方法中最终调用的是Handler(Callback callback, boolean async),在Handler(Callback callback, boolean async)中会通过Looper.myLooper()获取当前线程的Looper。

       Looper.myLooper()的源码如下

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
       在myLooper()方法中会通过sThreadLocal来获取的,sThreadLocal中的Looper对象通过上文对Looper的介绍可以知道是在线程调用Looper.prepare()时存放到ThreadLocal中的。

       sendMessage()的源码如下

public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

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

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
       通过代码可以看出,在外部调用了sendMessage(Message msg)之后最终执行的是enqueueMessage方法(send与post的一系列方法最终调用的都是enqueueMessage),所以我们主要关注enqueueMessage方法,在该方法中让要发送的Message对象持有当前Handler的引用(msg.target = this),最后将Message对象插入消息列表(queue.enqueueMessage(msg, uptimeMillis)),Looper在发现消息列表中有数据就会将消息取出并且交由Handler进行处理,即Handler的dispatchMessage方法会被调用,这时Handler就进入了处理消息的阶段。

       dispatchMessage()的源码如下

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();
    }
public void handleMessage(Message msg) {
    }
       通过代码可以看出,在dispatchMessage中优先处理Message中的callback,这个callback其实就是在post一系列方法中传递过来的Runnable,mCallback 是一个接口,是在Handler的构造方法中传递进来的,可以看到当mCallback 中的handleMessage方法返回值为true时Handler将不会执行Handler中handleMessage方法。

5.总结

       Handler会通过以下三步实现跨线程通信

  1. 系统在主线程ActivityThread中已经调用Looper.prepareMainLooper()创建主线程的Looper,并调用Looper.loop()启动轮询,不断地通过MessageQueue的next()方法从消息列表中取出消息,当没有消息是,next()处于阻塞状态,Looper.loop()也处于阻塞状态
  2. 当我们在Activity等运行在主线程的组件中创建Handler时,Handler通过Looper.myLooper()获取与当前线程也就是主线程关联的Looper对象,同时Handler也持有了Looper中的MessageQueue
  3. 子线程持有主线程创建的Handler对象,在子线程中通过Handler的send()或post()的系列方法发送消息,send()与post()的系列方法最终都是通过Handler持有的MessageQueue对象调用enqueueMessage方法将消息插入队列,触发在主线程主线程中轮询的Looper用过loop()取出消息,并在loop()中调用Handler的dispatchMessage()方法,将消息交由Handler处理,最终达到了子线程进行IO操作后发送消息,主线程做相应的消息处理


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值