美文网首页Android开发
Looper 消息机制 源码分析

Looper 消息机制 源码分析

作者: zhangyugehu | 来源:发表于2017-06-28 11:51 被阅读13次

    Looper 源码分析

    Looper
    构造方法初始化mLocalThreadmQueue

    static prepare():sThreadLocal取出当前此案称·线程已初始化的Looper对象,如果没有初始化Looper对象并存入sThreadLocal

    myLooper(): 返回sThreadLocal中当前线程的Looper对象

    loop(): 调用muLooper()取得当前线程的Looper对象,再从Looper对象中去的mQueue,然后开启死循环不断调用mQueue.next()方法取得Message对象从Message对象中获取发送该消息的Handler对象,再调用HandlerdispatchMessage()方法,将消息发送到HandlerhandleMessage() 方法中让用户进行处理。

    Message: 用于传输的消息实体类

    MessageQueue:

    单向链表实现的队列

    enqueueMessage() 将消息加入队列

    newxt() 从队列中取出消息

    Handler:

    消息辅助类,主要功能向消息池发送各种消息事件

    sendMessage(): 向消息队列发送消息

    handleMessage(): dispatchMessage()方法将从队列中取出的消息发送到此。让用户进行处理

    dispatchMessage(): 系统调用将从消息队列取出的消息发送给handleMessage()处理

    主要代码

    Looper.java

    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));
    }
    
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
    
    // 循环取出队列中消息去处理
    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;
        // ...
        for (;;) {
            Message msg = queue.next();
            // ...
            msg.target.dispatchMessage(msg);
            // ...
        }
    

    Handler.java

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
    
    public final boolean sendMessage(Message msg){
        return sendMessageDelayed(msg, 0);
    }

    相关文章

      网友评论

        本文标题:Looper 消息机制 源码分析

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