Handler、Looper、messagequeue源码分析及使用(2)

Handler、Looper、messagequeue源码分析及使用(1)
Handler、Looper、messagequeue源码分析及使用(2)

五、通过源码分析handler实现原理


1、先放一张handler的流程图,来有一个直观的印象。
流程图—来自于网络
2、handler的构造方法
    public Handler(Callback callback, boolean async) {
        .........
        // 获取当前线程的Looper对象
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        // 获取looper中的消息队列
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

构造方法很简单,只做了数据获取与保存操作,这里面比较重要是mLooper = Looper.myLooper();mQueue = mLooper.mQueue;
先来看看mLooper = Looper.myLooper();是哪来的,又是怎么创建获取的。

    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

通过ThreadLocal保存Looper,ThreadLocal保存的数据,仅限于各自的线程访问,简单的看下ThreadLocalset()方法

    public void set(T value) {
        // 获取当前线程
        Thread t = Thread.currentThread();
        // 根据线程获得ThreadLocalMap 对象,来保存数据
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

接着看下Looper是怎么创建,什么时候保存在ThreadLocal中的。

    private Looper(boolean quitAllowed) {
        // 在Looper创建时,同时构建一个MessageQueue的队列,保存消息
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

    public static void prepare() {
        prepare(true);
    }

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            // 确保当前线程只有一个Looper存在
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        // 创建Looper对象,并绑定到当前线程中
        sThreadLocal.set(new Looper(quitAllowed));
    }

Looper的构造方法是私有的,所以要想构造Looper对象,只能调用prepare(),在prepare()中创建了Looper并通过sThreadLocalLooper与当前线程绑定。

3、handler的sendMessage/post
  • sendMessage()方法
    public final boolean sendMessage(Message msg) {
        return sendMessageDelayed(msg, 0);
    }

sendMessage()实际上调用的是sendMessageDelayed()方法

    public final boolean sendMessageDelayed(Message msg, long delayMillis) {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

sendMessageDelayed()又调用sendMessageAtTime()方法,同时设定一个执行的指定时间,这个时间的参照基础是SystemClock.uptimeMillis()

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

sendMessageAtTime()一样是调用调用其他方法,并把成员变量mQueue也作为参数传递给enqueueMessage()

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

设置message的target为自身,并调用队列的enqueueMessage(),把消息插入到队列的指定位置。

boolean enqueueMessage(Message msg, long when) {
    if (msg.target == null) {
        // target必须设置值
        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) {
            // 如果线程正在消亡,则释放message资源,并打印日志说明
            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(); // 标记message状态为已使用
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
            // 如果消息队列为空/新消息执行时间为0/或者新消息执行时间早于当前队列头的执行时间,
            // 则设置新消息,为当前队列头。
            // 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中首先判断,如果当前的消息队列为空,或者新添加的消息的执行时间when是0,或者新添加的消息的执行时间比消息队列头的消息的执行时间还早,就把消息添加到消息队列头(消息队列按时间排序),否则就要找到合适的位置将当前消息添加到消息队列。

  • post()方法
    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;
    }

其实post()方法实际也是调用sendMessageDelayed()进行发送。

到这里你会不会有个疑问?从handler的构造到发送,只是创建LoopermessageQueue,把Message加入到messageQueue,并没有执行实际的消息发送,到底这个发送是什么时候执行的?要知道这个发送什么时候调用的,我们要看一下android的入口方法,ActivityThreadmain()方法

    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.loop();,它会开启消息队列MessageQueue的轮询,只要其中有消息message在轮询到的时候就会被调用,当MessageQueue没有消息时则处于等待状态。

4、Looper的looper()
    public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            // 还记得Looper的prepare()吗?
            // 调用loop()方法前,必须调用一次Looper.prepare(),否则会怕抛出此异常
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) { //此处是一个死循环,用于不断的遍历消息队列,从中获得消息并执行
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            // This must be in a local variable, in case a UI event sets the logger
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            // trace调用的是native,这里无法看到,但这个不影响我们对整个机制的理解
            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                // 还记得target赋值的是什么吗?ok.这个调用的是handler的dispatchMessage()
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }

            msg.recycleUnchecked(); // 释放message资源
        }
    }

loop每次从MessageQueue取出一个Message,调用msg.target.dispatchMessage(msg)handler.dispatchMessage(msg),而dispatchMessage()最终会调用我们熟悉的handleMessage()或者run()方法,执行完dispatchMessage(),这个消息资源就会被释放掉,然后重复这一流程。

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            // post的Runnable回调
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                // handler构造传入的CallBack回调
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            // handler自身的handleMessage方法
            handleMessage(msg);
        }
    }
    private static void handleCallback(Message message) {
        message.callback.run();
    }



Ps: 整个Handler的使用及分析到这里就算完毕,花了2,3天的时间算是断断续续的看完了这块,以前使用一知半解,现在看过整个源码,使用起来一定会得心应手啦,_

Handler、Looper、messagequeue源码分析及使用(1)
Handler、Looper、messagequeue源码分析及使用(2)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,657评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,889评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,057评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,509评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,562评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,443评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,251评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,129评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,561评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,779评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,902评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,621评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,220评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,838评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,971评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,025评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,843评论 2 354

推荐阅读更多精彩内容