Handler机制以及通常问题考察

今天我们就开始看看handle到底是怎么工作的

使用范例

Looper.prepare()
            val handler = Handler(Looper.myLooper()!!)
            val button = Button(this)
            val parms = WindowManager.LayoutParams(100f.dp.toInt(),100f.dp.toInt())
            parms.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            windowManager.addView(button,parms)
            handler.postDelayed({
                button.text = "hhhhhh"
            },5000)
            Looper.loop()

看看Looper.prepare()

public static void prepare() {
        prepare(true);
    }
<pre><code>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));
}

很简单,就是new了一个Looper,存在了自己线程,如果已经存过了就报错,所以每个线程只能有一个Looper

看看looper.loop

Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
msg.target.dispatchMessage(msg);</p>
<p>

loop中如果没有取到就直接return了,所以我们的loop要放在handle的post的后面

避免有未处理Message, 看看Handle的dispatchMessage

public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}</p>
<p>private static void handleCallback(Message message) {
message.callback.run();
}

是不是很简单,如果当时包装Message的是runable,直接就执行run方法了,不是则处理handleMessgae()