Android 消息机制 Handler、Looper与MessageQueue

版权声明:不为无益之事,何以遣有涯之生。 https://blog.csdn.net/lj402159806/article/details/82947744

Android 消息机制

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

MessageQueue就是消息队列,它内部存储了一组消息,以队列的形式对外提供插入和删除的工作,但内部存储结构不是真正的队列,而是采用单链表的数据结构来存储消息列表

Looper就是消息循环,它会以无限循环的形式去查找是否有新消息,有的话就处理消息,否则就一直等待

ThreadLocal被使用在Looper中,它并不是线程,它的作用是可以在每个线程中存储数据,Handler创建的时候需要当前线程的Looper来构造消息循环系统,就会使用到ThreadLocal来获取当前线程的Looper

Android 消息机制源码分析

Android的主线程就是ActivityThread,主线程的入口方法为main,源码如下:

public static void main(String[] args)
    ...
    Process.setArgV0("<pre-initialized>");
    Looper.prepareMainLooper();// 1.创建消息循环Looper

    ActivityThread thread = new ActivityThread();
    thread.attach(false);

    if(sMainThreadHanlder == null){
        sMainThreadHanler = thread.getHandler(); //UI线程的Handler
    }

    AsyncTask.init();
    ...
    Looper.loop(); // 2.执行消息循环

    throw new RuntimeException("Main thread loop unexp0ectedly exited");

主线程中通过Looper.prepareMainLooper()创建了一个消息队列,最后执行Looper.loop()来启动消息循环

首先来看下Looper.prepareMainLooper()方法:

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

//设置UI线程的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();
    }
}

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

prepareMainLooper()方法中调用了prepare()方法,在这个方法中创建了一个Looper对象,并且设置给sThreadLocal,最后将创建完的Looper对象传递给sMainLooper

Looper构造方法:

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

MessageQueue消息队列在Looper的构造方法中创建并关联,并将当前线程的对象保存起来

然后来看下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; // 1.获取消息队列
    ...
    for (;;) { // 2.死循环,即消息循环
        Message msg = queue.next(); // 3.获取消息(might block)
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }
        ...
        try {
            msg.target.dispatchMessage(msg); //4.处理消息
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        ...
        msg.recycleUnchecked(); //回收消息
    }
}

loop()方法其实就是建立一个死循环,然后从消息队列中逐个取出消息,最后处理消息的过程

用于去除消息的queue.next()源码:

Message next() {
    ...
    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;
            }
           ...
        }
        ...
    }
}

queue.next()是一个无限循环,如果消息队列中没有消息,那么会进行阻塞,当有新消息来时next方法会返回这条消息并将其从单链表中移除

msg.target.dispatchMessage(msg)消息处理机制:

msg是Message类型,源码如下:

public final class Message implements Parcelable{
    Handler target; //target处理
    Runnable callback; //Runnable类型的callback
    Message next; //下一条消息,消息队列是链式存储的
    ...
}

可以看到target是Handler类型,实际上就是调用Message内部关联handler的dispatchMessage(msg)方法

//消息处理函数,子类覆写
public void handleMessage(Message msg){
}

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

//分发消息
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

dispatchMessage是一个分发的方法,对应handler的两种消息发送方法,handleCallback对应post(Runnable callback),handleMessage对应sendMessage

public final boolean post(Runnable r){
    return sendMessageDelayed(getPostMessage(r), 0);
}

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

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

可以看到在post(Runnable r)时,会将Runnable包装成Message对象,并将Runnable对象设置给Message对象的callback字段,post与sendMessage最终都会调用sendMessageDelayed(msg,time)方法,最后调用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);
}

最终就是将消息追加到Messagequeue中

看一下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) {
        ...
        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中主要操作其实就是单链表的插入操作,然后我们可以看到使用了synchronized锁,在next方法中同样也使用了synchronized锁,这样就保证了在插入或取出消息时的数据同步性

最后来看一下Handler的构造方法:

public Handler(Callback callback, boolean async) {
    ...
    mLooper = Looper.myLooper(); //获取Looper
    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会在内部通过Looper.myLooper()来获取Looper对象,并且通过mLooper.mQueue来获取消息队列,如果myLooper()中无法从ThreadLocal获取到Looper对象的话就会抛出异常,这也就解释了在没有Looper的子线程中创建Handler会引发异常的原因

参考:

Android 开发进阶从小工到专家

Android 开发艺术探索

https://blog.csdn.net/lmj623565791/article/details/38377229/

https://blog.csdn.net/xxxzhi/article/details/52834439

猜你喜欢

转载自blog.csdn.net/lj402159806/article/details/82947744
今日推荐