美文网首页
Handler源码阅读

Handler源码阅读

作者: etrnel | 来源:发表于2019-03-10 09:52 被阅读0次

handler工作流程图 参考DonKingLiang的文章
图片老是上传失败,不知道为啥,本地和网络的都不可以。。。点链接看一下吧(ˉˉ;)...

发消息给MessageQueue

在子线程中使用handler发送消息

  Message message=Message.obtain();[图片上传失败...(image-96fef0-1552182500432)]

        message.obj="test";
        handler.sendMessage(Message.obtain());

Message.obtain()方法,带参数的obtain方法最终会回到obtain()方法,只是指定了对应的参数。

public static Message obtain() {
//从缓存池中取Message,如果没有的话再创建新的Message,避免重复创建新对象,浪费资源。
        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();
    }

handler.sendMessage()最终会调用MessageQueue的enqueueMessage(Message msg, long when)方法。
(handler.sendMessageAtFrontOfQueue()方法可以把消息插入到队列前,但是除了特殊情况不建议使用,谷歌有注释说明)

 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) {
//mQueue在handler构造器中已经初始化。
        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(MessageQueue queue, Message msg, long uptimeMillis) {
//指定msg的handler,在Looper的loop()中会用到
        msg.target = this;
//设置消息是否是异步,new handler源码的时候是false
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
//MessageQueue对Message根据uptimeMillis时间进行排序
        return queue.enqueueMessage(msg, uptimeMillis);
    }

MessageQueue中取消息

最后调用的是MessageQueue中的enqueueMessage方法。

boolean enqueueMessage(Message msg, long when) {
        // 判断有没有 target 
        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;
            // 第一次添加数据到队列中,或者当前 msg 的时间小于 mMessages 的时间
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                // 把当前 msg 添加到链表的第一个
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // 不是第一次添加数据,并且 msg 的时间 大于 mMessages(头指针) 的时间
                // 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 插入到列表中
                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;
    }

消息队列采用单链表,插入速度快。

Looper消息循环
在子线程直接new handler会报错,

    @Override
    public void run() {
        Handler handler = new Handler();
    }
}.start();

但是加入Looper后就可以正常运行。

new Thread(){
    @Override
    public void run() {
        Looper.prepare();
        Handler handler = new Handler();
        Looper.loop();
    }
}.start();

在activity中使用handler没有写looper的代码没有报错,是因为activity启动时在ActivityThread的main方法中帮我们调用了Looper。

public static void main(String[] args) {
//省略部分代码
        Looper.prepareMainLooper();
        ActivityThread thread = new ActivityThread();
        thread.attach(false);
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

首先看一下Looper.prepareMainLooper()方法。顾名思义,是用来初始化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));
    }
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

重点是ThreadLocal的set方法,保证一个线程只有一个looper,保证了线程的安全性。

  public void set(T value) {
  //value就是传过来的looper,将value存到ThreadLocalMap中。
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

最后看一下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;
   //从消息队列中不断取出Message
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            try {
//target就是绑定的handler,对msg进行分发处理。
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
//对messag进行循环处理。
            msg.recycleUnchecked();
        }
    }

Handler处理消息
handler对message进行处理,优先执行message和handler的callback,最后才是handleMessage方法。

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

到这里,handler的工作流程就走了一遍。大致就是Looper.prepareMainLooper() 创建了一个 Looper 对象,而且保证一个线程只有一个 Looper;Looper.loop() 里面是一个死循环,不断的从 消息队列 MessageQueue 中取消息,然后通过 Handler 执行。

相关文章

网友评论

      本文标题:Handler源码阅读

      本文链接:https://www.haomeiwen.com/subject/vpnspqtx.html