handler源码剖析

1.基本运用

handler:发送和承受音讯

looper:用于轮询音讯行列

MessageQueue:音讯行列用于存储音讯和办理音讯

//UI线程
val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.obj) {
                CODE_UPDATE -> {
                    //处理音讯
                }
            }
        }
    }
    Thread {
        val message = Message.obtain()
        message.what = CODE_UPDATE
        //发送音讯
        handler.sendMessage(message)
        //发送一条延时音讯 
        handler.sendMessageDelayed(message,200)
    }.start()
	Thread{
		handler.post {
        	// 在UI线程履行的使命
    	}
	}

1.创立handler目标

2.运用post办法或许sendMessage办法

3.在handler所在的线程,进行音讯处理

两种发送信息的方式,一种是发送Message,一种是post。

别离看下两种方式的源码处理

2.流程解析

2.1 handler创立

//android.os.Handler
public Handler(@NonNull Looper looper) {
    this(looper, null, false);
}
public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
        	mLooper = looper;
        	mQueue = looper.mQueue;
        	mCallback = callback;
        	mAsynchronous = async;
}
class Handler{
    final Looper mLooper;
    final MessageQueue mQueue;
    ...
}

可以看到,在handler创立的时分,需要传入一个looper,而mQueue被Looper所持有

2.2 looper创立

在ActivityThread中的main办法中,现已为我们创立了looper

android.app.ActivityThread
public static void main(String[] args) {
    ... 省掉代码
    //初始化looper和MessageQueue
    Looper.prepareMainLooper();
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }
    if (false) {
        Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread"));
     }
    ... 省掉代码
    //轮询
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

Looper.prepareMainLooper()进行了Looper和MessageQueue的创立


android.os.Looper
public static void prepareMainLooper() {
    //不行退出
    prepare(false);
    synchronized (Looper.class) {
        //假如looper现已存在,则抛出反常
        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));
}
public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}

从代码可以看出,主要是经过Looper.prepare办法进行创立looper,先调用sThreadLocal.get()获取Looper,假如Looper现已存在,则抛出反常。假如不存在,则创立Looper而且设置到ThreadLocal中。再来看看ThreadLocal的具体完成

android.os.Looper
public final class Looper {
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
}
java.lang.ThreadLocal
public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
 }
ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}
public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null){
        map.set(this, value);
    }else{
        createMap(t, value);
    }
}

ThreadLocal的作用是为每个线程提供一个独立的变量副本,经过ThreadLocalMap来完成对每个线程的变量副本的存储和获取。获取到当前线程对应的ThreadLocalMap,static final润饰的threadLocal变量作为key,value则是looper实例,进行存储。由于key永远是同一个,再加Looper.prepare会先判别当前线程是否存在looper,所以Looper在每个线程中只会存在一个Looper

2.3 MessageQueue创立

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

在looper的构造函数中,创立了MessageQueue,这个时分handler和looper,messagequeue就绑定在一起了。

2.4 handler.sendMessage

android.os.Handler
public final boolean sendMessage(@NonNull Message msg) {
    return sendMessageDelayed(msg, 0);
}
public final boolean post(@NonNull Runnable r) {
    return sendMessageDelayed(getPostMessage(r), 0);
}
    //post 将runnable设置为msg的callback
private static Message getPostMessage(Runnable r) {
        	Message m = Message.obtain();
        	m.callback = r;
        	return m;
    	}
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(@NonNull 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(@NonNull MessageQueue queue, @NonNull Message msg,
            long uptimeMillis) {
    msg.target = this;
    msg.workSourceUid = ThreadLocalWorkSource.getUid();
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

经过上面的代码可以看出,无论是sendMessage还是post都会走到sendMessageDelayed,在走到sendMessageAtTime办法,uptimeMillis则是一个具体的时刻点,最终走到了enqueueMessage办法,msg.target = this,指向了当前handler。最终由queue.enqueueMessage进行处理。在一开始创立handler的时分,现已看到了mQueue是MessageQueue。接下来看MessageQueue是怎样处理这个音讯的

android.os.MessageQueue
boolean enqueueMessage(Message msg, long when) {
    if (msg.target == null) {
        throw new IllegalArgumentException("Message must have a target.");
    }
    //加锁
    synchronized (this) {
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }
        //Looper.myLooper().quit(); 使用退出的时分才会被符号为true
        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) {
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
            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;
            }
        }
        //唤醒
        if (needWake) {
            nativeWake(mPtr);
        }
        return true;
    }

刺进行列这儿进行了加锁,保证了线程安全。从代码看出这个行列是优先级行列,依照msg的when进行排序。当头节点为null或许头节点的when大于msg的when时,msg作为头节点。假如msg的when大于头节点,轮询将msg刺进到适宜的位置。

2.5 Looper.loop

现已将msg刺进到messagequeue中,接下来看看loop是怎样处理的。

android.os.Looper
public static void loop() {
    //获取looper
    final Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    for (;;) {
        if (!loopOnce(me, ident, thresholdOverride)) {
            return;
            }
        }
    }
}
private static boolean loopOnce(final Looper me,final long ident, final int thresholdOverride) {
    //取出行列中的音讯
    Message msg = me.mQueue.next(); // might block
    if (msg == null) {
        return false;
    }
    ...省掉代码
    //msg.target就是handler
     msg.target.dispatchMessage(msg);
    ...省掉代码
    msg.recycleUnchecked();
    return true;
}
android.os.MessageQueue
Message next() {
    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) {
            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) {
                    //计算休眠的时刻
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    // 获取音讯并回来
                    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 {
                // 没有音讯 一向堵塞
                nextPollTimeoutMillis = -1;
            }
            if (mQuitting) {
                dispose();
                return null;
            }
            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);
        }
        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);
                }
            }
        }
        pendingIdleHandlerCount = 0;
        nextPollTimeoutMillis = 0;
    }
}

在循环中,程序不断地从音讯行列中获取音讯。假如成功获取到音讯,程序会判别当前时刻是否小于音讯的触发时刻(msg.when)。假如是,管帐算出下一次轮询超时的时刻(nextPollTimeoutMillis),然后经过调用nativePollOnce办法来进行等候,该办法底层会调用Linux的epoll办法。

假如当前音讯行列中没有任何音讯,程序将会无限等候,直到有新的音讯到达。这个进程会不断重复,保证程序可以及时处理音讯

msg.target是handler,在取出msg后,最终会调用到handler的dispatchMessage办法。接下来又会履行msg.recycleUnchecked()办法。

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 = UID_NONE;
        workSourceUid = UID_NONE;
        when = 0;
        target = null;
        callback = null;
        data = null;
        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

这儿将msg的符号进行置空,释放一切资源,在判别当前行列的msg数量是否小于MAX_POOL_SIZE(50),假如小于则刺进到表头。

2.6 Handler.dispatchMessage

public void dispatchMessage(@NonNull Message msg) {
    //post runnable设置msg的callback
    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();
}

假如是post过来的音讯,一开始传入的时分现已将runnable设为msg的callback,这个时分直接履行run函数,否则由handler的callback回调处理。