Android Framework源码分析----Handler、Message、MessageQueue、Looper

Message:线程间通讯的消息体

Handler: 主要是负责发送消息,和接收消息

MessageQueue:负责以队列的方式存储消息

Looper: 就是一直轮询的从MessageQueue中取消息,获取到消息就通过dispatchMessage()将消息发送给Handler去处理。

举例理解一下:

平常生活中,从网上购物,商家把一个商品打包好后,将邮件投递给了快递公司,快递公司就从投递的网点取出来邮件,然后根据邮件上的地址将邮件发送给收件人,那么这里的邮件就是Message , 而快递公司的收寄网点就像是MessageQueue ,然后快递公司取到邮件后按照地址发送邮件,就类似Looper , 最后收件人接收快递。

这样理解,就可以明白这其实就是一种生产者消费者的模式。

Handler原理.png

一、Message消息

1、Message创建

下面三种获取消息的方式基本上类似:

从全局池中获取新的消息实例,这样就可以达到复用用过的消息,避免创建销毁消息对象,这样性能和内存上都比直接new一个消息要好。

//Message.java
    /**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     */
    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

    /**
     * Same as {@link #obtain()}, but copies the values of an existing
     * message (including its target) into the new one.
     * @param orig Original message to copy.
     * @return A Message object from the global pool.
     */
    public static Message obtain(Message orig) {
        Message m = obtain();
        m.what = orig.what;
        m.arg1 = orig.arg1;
        m.arg2 = orig.arg2;
        m.obj = orig.obj;
        m.replyTo = orig.replyTo;
        m.sendingUid = orig.sendingUid;
        m.workSourceUid = orig.workSourceUid;
        if (orig.data != null) {
            m.data = new Bundle(orig.data);
        }
        m.target = orig.target;
        m.callback = orig.callback;

        return m;
    }

    /**
     * Same as {@link #obtain()}, but sets the value for the target member on the Message returned.
     * @param h  Handler to assign to the returned Message object's target member.
     * @return A Message object from the global pool.
     */
    public static Message obtain(Handler h) {
        Message m = obtain();
        m.target = h;

        return m;
    }


//这里也可以给message设置一个处理message的callback ,在Handler处理消息的时候使用
    public static Message obtain(Handler h, Runnable callback) {
        Message m = obtain();
        m.target = h;
        m.callback = callback;

        return m;
    }

二、Handler消息发送与消费流程

1、发送消息

//Handler.java
   public final boolean sendMessage(@NonNull Message msg) {
       //注意这里传入的第二个参数delayMillis  为 0 
        return sendMessageDelayed(msg, 0);
    }

    public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        //继续进入sendMessageAtTime()
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

   public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
       //这里为什么要讲成员变量mQueue赋值给一个局部变量呢?笔者猜想这样如果出现对mQueue的多线程操作,就不会导致阻塞;
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
       //这里传入enqueueMessage的第三个参数不在是0 ,已经修改了的
        return enqueueMessage(queue, msg, uptimeMillis);
    }

    private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
            long uptimeMillis) {
        msg.target = this;//这里的this就是当前的Handler,这样msg就和当前的Handler绑定在一起了
        msg.workSourceUid = ThreadLocalWorkSource.getUid();

        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        
        //这里就会进入到MessageQueue的enqueueMessage()方法中去
        return queue.enqueueMessage(msg, uptimeMillis);
    }

至此,Handler通过sendMessage 一步一步将msg 加入到MessageQueue中,这样就完成了消息的发送。

2、消费消息

根据上面的Handler运行机制我们可以知道,从消息队列获取消息是在Looper的loop中通过一个无限循环来完成,然后通过获取到的消息target(也就是在发送消息时传入的Handler)来讲消息dispatchMessage()分发出去。关于Looper中获取消息会在第四部分分析,这里就只从Handler的dispatchMessage()开始。

//Handler.java
/**
     * Handle system messages here.
     */
    public void dispatchMessage(@NonNull Message msg) {
        if (msg.callback != null) {
            //1)处理消息1:如果在msg中设置了callback ,那么就会从这里进行消息的处理
            handleCallback(msg);
        } else {
            //2)处理消息2:这里的mCallback是一个接口类型,也就说需要将该接口的实例对象传递进来就会走这里的分支,调用其handleMessage()方法
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //3)处理消息1:重写handleMessage
            handleMessage(msg);
        }
    }

    private static void handleCallback(Message message) {
        message.callback.run();
    }

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

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

//1. 消息创建时传入callback ,就会使用消息自带的callback来处理消息
    public static Message obtain(Handler h, Runnable callback) {
        Message m = obtain();
        m.target = h;
        m.callback = callback;

        return m;
    }

//2. 给Handler设置callback
    public Handler(@Nullable 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 " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

    public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

消费消息有三种方式:

  1. 在创建Message设置自己的callback
  2. 在创建Handler消息是,给Handler对象设置callback(注意这类构造是hide)
  3. 重写Handler的handleMessage()方法(这种也是最常见的)

Handler的工作流程:

Handler通过发送一个消息,将消息加入到消息队列中,然后Looper从消息队列中取出消息后通过Handler的dispatchMessage()将消息分发出去,消息的处理可以有Message自带的callback 、handler的callback 或者重写的handler的handleMessage()来完成消息的消费。

三、MessageQueue分析

MessageQueue作为一个存储消息的队列容器,那么他的核心就是消息的存储和取出。

1、消息入队(enqueueMessage)

  1. 在入队时使用了Synchronized锁,锁的是this,也就是说对同一个MessageQueue对象的所有调用者来说,都是互斥的,他们必须等到上一个调用者释放了锁,后面调用者才能执行锁中的代码;
  2. 在消息加入队列的时候,会按照消息执行的时间顺序进行队列的排序;
//MessageQueue.java
boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }

    //这里的synchronized锁需要注意一下
        synchronized (this) {
            if (msg.isInUse()) {
                throw new IllegalStateException(msg + " This message is already in use.");
            }

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

2、消息出队(next)

消息出队主要就是将队列的首部取出,因为在入队的时候已经按照时间进行了排序;

在取消息时也使用了synchronized锁,这个锁是用来针对调用者enqueueMessage、next只能执行一个操作,不能同时进行,这样就可以保证消息的不同线程访问的时候有序的进行。

//MessageQueue.java
 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);
            }//这里就synchronized就结束了

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

3、同步屏障

根据上面的内容,消息的发送是同步的(即按照排队顺序一条一条执行),如果有一条紧急的消息需要处理时,按照常规就需要继续排队,等到满足了自己执行的条件再处理该消息,那么这时候同步屏障就来了,同步屏障说白了就是开通的消息的绿色通道。

例如:在高速上遇到堵车的情况,常规就应该排队等待,高速的应急车道就可以理解成是同步屏障,这样可以处理一些紧急的事情。

3.3.1 设置同步屏障:

//MessageQueue.java
    public int postSyncBarrier() {
        return postSyncBarrier(SystemClock.uptimeMillis());
    }

//注意下下面并没有给msg设置target
private int postSyncBarrier(long when) {
        // Enqueue a new sync barrier token.
        // We don't need to wake the queue because the purpose of a barrier is to stall it.
        synchronized (this) {
            final int token = mNextBarrierToken++;
            final Message msg = Message.obtain();
            msg.markInUse();
            msg.when = when;
            msg.arg1 = token;

            Message prev = null;
            Message p = mMessages;
            if (when != 0) {
                while (p != null && p.when <= when) {
                    prev = p;
                    p = p.next;
                }
            }
            if (prev != null) { // invariant: p == prev.next
                msg.next = p;
                prev.next = msg;
            } else {
                msg.next = p;
                mMessages = msg;
            }
            return token;
        }
    }

3.3.2 Looper取消息时处理同步屏障

  1. 由于在设置同步屏障时并没有给msg设置target ,所有就会进入下面的do while里;
  2. while的条件(isAsynchronous 默认是false ,msg 也不为Null),所以会循环执行
  3. msg 每一次循环都会获取下一条消息,也就是会变量消息队列中的所有消息执行;
  4. 屏障在执行,下面的同步代码块就不会执行,需要等待;
  5. 需要溢出同步屏障后方可执行后面的同步代码块;
//MessageQueue.java
 Message next() {   
        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) {
                    // 这里就是处理同步屏障消息的
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
              //.......此处省略了很多代码 
            }
        }
    }

//移除同步屏障
 public void removeSyncBarrier(int token) {
        // Remove a sync barrier token from the queue.
        // If the queue is no longer stalled by a barrier then wake it.
        synchronized (this) {
            Message prev = null;
            Message p = mMessages;
            while (p != null && (p.target != null || p.arg1 != token)) {
                prev = p;
                p = p.next;
            }
            if (p == null) {
                throw new IllegalStateException("The specified message queue synchronization "
                        + " barrier token has not been posted or has already been removed.");
            }
            final boolean needWake;
            if (prev != null) {
                prev.next = p.next;
                needWake = false;
            } else {
                mMessages = p.next;
                needWake = mMessages == null || mMessages.target != null;
            }
            p.recycleUnchecked();

            // If the loop is quitting then it is already awake.
            // We can assume mPtr != 0 when mQuitting is false.
            if (needWake && !mQuitting) {
                nativeWake(mPtr);
            }
        }
    }

四、Looper 分析

1、Looper的创建

  1. 创建Looper时,给mQueue构造方法传入了是否允许退出的值为true ,是因为Message的quit()方法,如果传入的是false ,那么调用quit()会抛出 ' Main thread not allowed to quit. ' 的异常
  2. 创建主线程Looper其实和prepare基本上是一致的,只是传入的quitAllowed的值为false
//Looper.java
public static void prepare() {
        //这里默认传入的是否允许退出为:true
     prepare(true);
}

private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
       throw new RuntimeException("Only one Looper may be created per thread");
    }
    //这里进入Looper的构造函数,构造的参数传入的是false
    //把创建好的Looper对象加入到ThreadLocal中
    sThreadLocal.set(new Looper(quitAllowed));
}

private Looper(boolean quitAllowed) {
    //这里创建了一个消息队列
     mQueue = new MessageQueue(quitAllowed);
    //获取当前线程
     mThread = Thread.currentThread();
}

//》》》》》》》》》》》》》》》》》》》》》》》》》》》》
//准备一个主线程Looper
    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();
    }

2、Looper开始工作

  1. 获取创建好的Looper对象
  2. 从Looper对象中获取消息队列
  3. 通过一个死循环从消息队列中去消息,如果消息队列中有消息,就调用消息体中的Target进行DispatchMessage()
//Looper.java
 public static void loop() {
        //这里取出来之前创建好的Looper对象
        final Looper me = myLooper();
        if (me == null) {
            //如果没有Looper对象,就会抛出需要调用prepare()的异常
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
  
        final MessageQueue queue = me.mQueue;
        for (;;) {
            //这里是一个死循环,从消息队列中取消息
            Message msg = queue.next(); // might block
            if (msg == null) {
                return;
            }

            try {
                //这里通过消息体中的target调用dispatchMessage()来分发消息
                msg.target.dispatchMessage(msg);
                if (observer != null) {
                    observer.messageDispatched(token, msg);
                }
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } catch (Exception exception) {
                throw exception;
            } finally {
                ThreadLocalWorkSource.restore(origWorkSource);
            }
        }
    }

3、Looper结束工作

//Looper.java
   public void quit() {
        mQueue.quit(false);
    }


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

总结:

一个线程对应一个Looper, 一个Looper包含一个MessageQueue,这样多个Handler在发送消息时,通过MessageQueue中的同步锁来达到线程同步的目的,消息队列采用链表的结构来对消息进行排序,Looper通过一个无限循环从消息队列中取消息。然后再通过Message的Target进行dispatchMessage,然后进入Handler的hanleMessage()处理消息。

你可能感兴趣的:(Android Framework源码分析----Handler、Message、MessageQueue、Looper)