2021-03-09

Android应用程序是通过消息来驱动的,当Android主线程启动时就会在内部创建一个消息队列。然后进入一个无限循环中,轮询是否有新的消息需要处理。如果有新消息就处理新消息。如果没有消息,就进入阻塞状态,直到消息循环被唤醒。

那么在Android系统中,消息处理机制是怎么实现的呢?在程序开发时,我们经常会使用Handler处理Message(消息)。所以可以知道Handler是个消息处理者,Message是消息主体。除此之外还有消息队列和消息轮询两个角色。它们分别是MessageQueue和Looper,MessageQueue就是消息队列,Looper负责轮询消息。

简介
我们已经知道Android的消息机制处理主要由Handler、Message、MessageQueue、Looper四个类的实现来完成。那么它们之间的关系是怎样的?

其中,Message是消息主体,它负责存储消息的各种信息,包括发送消息的Handler对象、消息信息、消息标识等。MessageQueue就是消息队列,在其内部以队列的形式维护一组Message(消息)。Handler负责发送和处理消息。Looper负责轮询消息队列。
在这里插入图片描述
Android消息机制原理
创建线程消息队列
在Android应用程序中,消息处理程序运行前首先要创建消息队列(也就是MessageQueue)。在主线程中,通过调用Looper类的静态成员函数prepareMainLooper()来创建消息队列。在其他子线程中,通过调用静态成员函数prepare()来创建。
/**
* 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()}
* 用来初始化主线程中的Looper,有Android环境调用,不应该有用户调用.
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException(“The main Looper has already been prepared.”);
}
sMainLooper = myLooper();
}
}

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

 /** 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()}.
  * 交给用户自己调用,通过loop()方法开启消息循环.同时当不需要处理消息时,需要手动调用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));
}

在这两个函数调用的过程中,sThreadLocal变量都有被使用。这个变量是ThreadLocal类型的,用来保存当前线程中的Looper对象。也就是说在Android应用程序中每创建一个消息队列,都有一个并且是唯一 一个与之对应的Looper对象。而且我们可以从源码中看到当对象不唯一时就会抛出异常。

private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed); //创建消息队列
mThread = Thread.currentThread();
}
从上面的源码中可以看到,当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(); // 在接收消息时有可能阻塞
        if (msg == null) {
            //message为null时,退出消息循环
            return;
        }

        // This must be in a local variable, in case a UI event sets the logger
        final Printer logging = me.mLogging;
        if (logging != null) {...}

        final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

        final long traceTag = me.mTraceTag;
        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {...}
        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) {...}
        }

        if (logging != null) {...}

        // Make sure that during the course of dispatching the
        // identity of the thread wasn't corrupted.
        final long newIdent = Binder.clearCallingIdentity();
        if (ident != newIdent) {...}
        msg.recycleUnchecked();
    }
}

上面的源码就是消息循环的过程,只用调用了loop()方法消息循环才开始起作用。当循环开始时:

获取当前线程的Looper对象,如果为null,抛出异常;

获取消息队列,开始进入消息循环;

从消息队列中获取消息(调用MessageQueue的next()方法),如果为null,结束循环;否则,继续执行;

处理消息,回收消息资源( msg.recycleUnchecked())。

在消息循环过程中,通过MessageQueue的next()方法提供消息,在没有信息时进入睡眠状态,同时处理其他接口。这个过程至关重要,通过next()方法也决定了消息循环是否退出。
Message next() {
final long ptr = mPtr; //与native方法相关,当mPtr为0时返回null,退出消息循环
if (ptr == 0) {
return null;
}

    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;  //0不进入睡眠,-1进入书面
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            //处理当前线程中待处理的Binder进程间通信请求
            Binder.flushPendingCommands();  
        }
        //native方法,nextPollTimeoutMillis为-1时进入睡眠状态
        nativePollOnce(ptr, nextPollTimeoutMillis); 
        synchronized (this) {
            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.
        //非睡眠状态下处理IdleHandler接口
        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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值