Android消息机制Handler,MessageQueue,Looper源码解析

这里写图片描述

首先我们先给大家介绍下Handler与Looper与MessageQueue整体运作
Handler:用于处理Message,可以有多个实例
Message:用于线程之间传递信息,发送的信息放入MessageQueue中
MessageQueue:是一个消息队列,用来存储Message信息,每个线程只有一个实例。
Looper:每个线程只有一个Looper,他是一个无限循环,不断地从MessageQueue中取出Message,发给handler处理

如图所示,我们通过handler发送一个消息,消息放入MessageQueue这个消息队列里面,Looper无限循环去检测MessageQueue是否有消息需要处理,looper将处理(ui更新)交至handler,也就实现了由子线程切换到主线程了。

带着这个主干,我们从源码方面进行解析:

Message

Message经常被用来传输,那么它可以传输哪些数据呢?

  1. arg1,arg2整数类型
  2. Object 类型obj
  3. What 用户自定义的信息代码,每个handler都有自己的信息代码,所以不用担心多个handler发送信息冲突。
  4. Bundle数据传输

Message中有几个属性先介绍下,后面会有用到,

  1. next:下一个可用对象,可以访问下一个可用的Message
  2. when:表示该消息的等待时间
  3. target:一个Handler对象,looper中将信息处理由该对象传回主线程

我们平时创建Message对象都是通过Message msg=new Message();但是不推荐这种方式,推荐使用Message msg=Message.obtain();为什么呢?

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

上面的注释写到:从全局池中返回一个新的消息实例,让我们避免在许多情况下分配新的对象。

这个说的很明确了,Message内部有一个回收池,如果回收池部位null那
就直接重用回收池中的消息,不用重新分配空间,节省资源。sPoll是回收头的消息,next是下一个可用的消息,放置头部等待下次使用。

既然有个回收池,那就看看怎么回事吧,

/**
 * Recycles a Message that may be in-use.
 * Used internally by the MessageQueue and Looper when disposing of queued Messages.
 */
void recycleUnchecked() {
    // Mark the message as in use while it remains in the recycled object pool.
    // Clear out all other details.
    flags = FLAG_IN_USE;
    what = 0;
    arg1 = 0;
    arg2 = 0;
    obj = null;
    replyTo = null;
    sendingUid = -1;
    when = 0;
    target = null;
    callback = null;
    data = null;

    synchronized (sPoolSync) {
        if (sPoolSize < MAX_POOL_SIZE) {
            next = sPool;
            sPool = this;
            sPoolSize++;
        }
    }
}

注释说到:回收一个消息,可以使用,通过MessageQueue和Looper在处理消息队列内部消息时使用

通过recycleUnchecked方法对Message对象的回收,就是把这个消息标记为可使用,并且将其他信息(属性)初始化,最终这个Message会在MessageQueue和Looper中使用。

MessageQueue——一个线程只有一个

MessageQueue是一个消息队列,用来存储Message,虽然说MessageQueue是一个消息队列,但是它的底层实现是一个单链表,既然是存储的,那就涉及到了插入和删除,而正好聊表在增加和删除方面有着优势,

  • 插入
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;
}

既然是单链表的插入,那么大家可能就会有疑问了,是头插呢还是尾插。
从上述代码中我们发现这里的插入方法既有头插,也有插入链表中间,插入位置取决于当前插入信息的等待时间

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

当消息队列中没有消息或者当前消息的等待时间为0或者当前消息的等待时间小于链表头的消息的等待时间,就进行头插法。
否则根据当前消息的等待时间按照升序方式插入到指定位置(有点像插入排序有木有)
这个等待时间就是我们

public final boolean sendMessageDelayed(Message msg, long delayMillis)

平时使用的那个sendeMessageDelayed方法中的delayMillis

  • 删除
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就会返回这条消息并从单链表中删除

Looper ——一个线程只有一个

Looper在消息机制中扮演的是消息循环的角色,它会不停地检索MessageQueue中是否有新的消息,如果有就立刻处理,没有就会阻塞在那里。
那么我们看下构造方法

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

Looper的构造方法就是对MessageQueue进行了初始化
因为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 traceTag = me.mTraceTag;
            if (traceTag != 0) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

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

主要的环节就在中间的一个for(;;)死循环
通过queue.next()读取MessageQueue中的消息,并且从MessageQueue中移除,取得了Message,就可以对其进行处理了。

msg.target.dispatchMessage(msg);

处理完后对其进行回收

 msg.recycleUnchecked();

这里我们发现从当前线程切换到了handler创建的线程中执行消息处理,
MessageQueue和Looper和Message的操作都是在子线程中进行,
而Handler是在主线程。
最终消息的处理还是回归到了UI线程,这正好符合在主线程更新UI的逻辑。

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

这个就是处理消息的具体细节了。一说到处理消息的具体细节实现我们应该会想到接口或者抽象方法,没错在Handler中就存在着接口和需要子类实现的方法,等在子类去继承自己去实现(如何处理消息)。

在上述代码有三次处理

  1. msg.Callback——–>handleCallback()
  2. mCallback———->mCallback.handleMessage()
  3. handleMessage()
Runnable callback;

在Message中callback 是一个Runnable,就是Handler中post(Runnable)的那个,

public interface Callback {
    public boolean handleMessage(Message msg);
}

mCallback回调接口

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

子类必须实现此接收消息

具体的处理细节是我们自己去实现,而这些刚好都是些接口,回调的需要实现的方法,这里我们应该想起来我们平时创建Handler的几种方式了吧。

  1. post(Runnable)
Handler handler2=new Handler();
handler2.post(new Runnable() {
    @Override
    public void run() {
        mTextView.setText("post方式发送消息并处理消息");
        Log.d(TAG, "CallBack");
    }
});

2.Callback回调

Handler  handler1=new Handler(handlerCallBack);
handler1.sendEmptyMessage(1);

3.派生Handler类

MyHandler myHandler=new MyHandler();
myHandler.sendEmptyMessage(1);

4.实例化Handler

Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        mTextView.setText("实例类实现接受消息");
        super.handleMessage(msg);
    }
};
handler.sendEmptyMessage(1);

这就是我们平时经常创建,使用Handler的方式。
这下我们应该理解Handler对消息的处理方式了吧

  1. 他会判断Message的回调事件(Runnable)是否为null,
    如果不为null,执行handleCallback(msg)
    如果是null,

  2. 判断Handler的Callback回调接口是否为null 如果不为null,执行handleMessage(msg)
    如果是null,

  3. 则执行Handler的方法handleMessage(msg)

到此Message信息就处理完了。

因为Loooper的loop方法是无限循环,因此Looper中提供了两个退出方法quit和quitSafty,一个立刻退出Looper,一个是设置退出标记,等待MessageQueue中的任务执行完毕在完全退出。而这两个方法也会调用MessageQueue的quit和quitSafty方法将Message的next设置为null。

但是,

细心地人可会产生疑问

  1. Handler只讲了发送消息。
  2. MessageQueue是消息队列,进行存储消息
  3. Looper中初始化MessageQueue,并且使用next处理消息队列中的消息

那么消息是怎么加入进去消息队列的,Looper又是在什么时候初始化的,存储在哪.

  1. 消息是如何加入消息队列的呢,前面讲了消息队列加入消息是MessageQueue中的enqueueMessage方法,其实我们post、sendMessage的时候最终都会调用到enqueueMessage(msg)
  2. Looper是Handle中初始化的
  3. Looper存储在ThreadLocal.Values localValues中的table数组中

到现在我们就要将最后两个类Handler和ThreadLocal

Handler

构造方法

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

从构造方法中明显就可以看出对Looper进行了初始化并且将Looper中的MessageQueue对象赋给了Handler中的MessageQueue 对象

我们看看Looper.myLooper()是什么。

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

我们看到了我刚才提示的ThreadLocal,那么ThreadLocal是个什么东东呢。

ThreadLocal

ThreadLocal是一个线程内部的数据存储类,可以在指定的线程中存储数据,数据存储以后,只有在指定线程中可以获取到存储的数据。ThreadLocal可以用于哪些使用场景呢,一般来说,当某些数据是以线程为作用域,并且不同线程具有不同的数据副本,那么就可以考虑采用TreadLocal了,对于Handle来说,他要获取当前线程的Looper,通过Looper去进行消息循环处理,很显然,Looper的作用域就是当前线程,并且不同的线程具有不同的Looper,这个时候就可以通过ThreadLocal轻松存取Looper了。

如果我们不采用ThreadLocal,那么系统就得提供一个全局哈希表供Handler查找指定线程的Looper,这样就得创建一个类似LooperManager的管理类去进行管理,显然没有直接使用ThreadLocal好。

在Looper、ActivityThread以及AMS中都用到了ThreadLocal。

ThreadLocal的内部有一个ThreadLocal.Values localValues成员,该成员内部有一个数组table,Looper的值就存在这里面

通过put代码我们可以得出一个存储规则,那就是ThreadLocal的值是在ThreadLocal的reference字段所标识的对象的下一个位置。get中也是获取到ThreadLocal的reference字段的存储位置,返回数组的下一个元素。

从get 和put方法我们所操作的对象都是当前线程的localValues 对象的table数组,因此在不同的线程访问同一个ThreadLocal的get和set方法,它们对ThreadLocal所进行的读写操作仅限于各自线程的内部.

讲到这里基本也就结束了。

我们最后在捋一遍:

Handler在初始化的时候就获取到了当前线程的Looper,通过post(Runnable),Callback回调接口,派生子类来创建一个handler,然后发送消息,最终他们都会执行enqueueMessage(msg)把消息加入到消息队列MessageQueue里面去。

MessageQueue是一个消息队列用来存储消息,但是它的底层实现是单链表,因为单链表在插入和删除更有优势,,而且插入的时候是根据每个消息的等待时间when升序插入的,提高了效率。

之后通过Looper和MessageQueue的next方法进行一个读取消息的操作,最后loop方法中调用了msg.target.dispatchMessage,msg.target是一个handler对象,最终消息的处理还是交给了handler,进行三次判空处理,执行消息处理。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值