Handler源码分析

微信截图_20210303172720.png

在子线程中获取完数据后需要更新ui的时候,往往会创建一个Handler实例,然后调用它的sendEmptyMessage等方法,接着在回调方法handleMessage中进行ui的刷新;

handler.sendEmptyMessage(1000);
private final Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //进行ui刷新动作

        }
    };

在Handler源码中可以看到这样的描述:

A Handler allows you to send and process {@link Message} and Runnable
objects associated with a thread's {@link MessageQueue}.  Each Handler
instance is associated with a single thread and that thread's message
queue. When you create a new Handler it is bound to a {@link Looper}.

一个消息处理程序允许发送消息实体和消息队列,任何一个消息处理程序都与一个线程和该线程的消息队列关联,创建新的处理程序是,会绑定到消息轮询器上面。这样Handler就和Message、MessageQueue、Looper之间相互关联了。

Handler:消息处理
Message:消息实体
MessageQueue:消息队列
Looper:消息轮询

同时得到一个信息:

Looper和当前线程是唯一的关系,一个线程对应一个Looper,并且Looper所在线程必须和当前线程保持一致。

在上面更新ui的代码中只是通过Looper.getMainLooper()获取了一个Looper实例,并没有任何创建Looper对象,程序并有出现任何错误,这是为什么呢?不是说任何一个消息处理对象都会和一个线程、该线程的消息队列、该线程的Looper相关吗?是的,应用程序在启动的时候会创建一个ActivityThread实例,并调用程序入口main方法,

public static void main(String[] args) {
        .......
        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"));
        }
        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

在main方法中调用了Looper.prepareMainLooper(),进行了主线程中Looper的创建,

@Deprecated
    public static void prepareMainLooper() {
        //调用prepare方法进行looper的创建
        prepare(false);
        synchronized (Looper.class) {
            //确保线程和Looper的唯一性  如果当前线程中已经存在有looper了 再调用prepare方法去创建就会报错
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            //对looper进行赋值
            sMainLooper = myLooper();
        }
    }

看的出prepareMainLooper是在住线程中创建对应的looper,其最终looper的创建还是交给了prepare方法去创建,如果要在子线程中创建对应的looper就需要调用prepare方法,

private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            //一个looper只能在一个线程中被创建 重复创建会出现错误
            throw new RuntimeException("Only one Looper may be created per thread");
        }
    //其实就是直接通过new的方式创建一个looper实例,并添加到一个静态的ThreadLocal中进行缓存
        sThreadLocal.set(new Looper(quitAllowed));
    }

sTheadLocal是一个静态的ThreadLocal,将创建好的looper缓存在ThreadLocal中,需要的时候通过myLooper方法去获取,保证looper实例的唯一性,

public static @Nullable Looper myLooper() {
    //获取之前创建并缓存的looper实例
        return sThreadLocal.get();
    }

looper实例已经创建好了,但是对应的MessageQueue还没有创建好呀,MessageQueue的实例是在looper的构造方法中进行实例好的,

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

调用prepare方法,就将looper实例和MessageQueue实例就都创建好了,创建好后就可以调用发送消息实体的方法进行消息的发送了,发送消息的方法有不少呢,

public final boolean sendMessage(@NonNull Message msg);
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis);
public final boolean sendEmptyMessage(int what);
public final boolean sendEmptyMessageDelayed(int what, long delayMillis);
public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis);

1和2是直接发送一个Message消息实体,区别是是否延时发送,后面这几种的话发送的是一个int类型的标识,区别也是是否延迟发送,虽然发送的是一个int类型的标识,但是最终发送的时候会调用Message.obtain()获取一个Message实例,并将标识封装进去,最终发送的还是一个Message消息实体,

public static Message obtain() {
        synchronized (sPoolSync) {
            //sPool 就是一个静态的Message实例 如果为null 下面就直接通过new 创建一个Message
            if (sPool != null) {
                Message m = sPool;
                //这里是单向链表的结构
                sPool = m.next;
                //获取到后 会将其设置为null
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                //将获取到的message实例返回
                return m;
            }
        }
        return new Message();
    }

上面那些方法最终都会调用sendMessageAtTime方法进行消息的发送,

public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
        //mQueue 的赋值在创建Handler时 通过mLooper.mQueue进行赋值了,如果没有创建MessageQueue实例 肯定会报错 并且中断消息的发送
        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);
        }
    //将消息的发送、处理等放到了MessageQueue中
        return queue.enqueueMessage(msg, uptimeMillis);
    }
boolean enqueueMessage(Message msg, long when) {
    //target就是当前对应的Handler实例 在Handler enqueueMessage方法中 msg.target = this;进行赋值了
        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.");
            }

            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) {
                //满足mMessages为null MessageQueue中没有消息  第一次添加时
                //或者不延时发送时 不延时发送放在队头 便于直接发送
                //或者当前消息发送的时间小于 MessageQueue中已存消息 队头消息的发送时间
                // 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;
    }

消息添加完毕后,肯定就是取消息了,是通过loop方法进行取消息的,但是之前更新ui的代码中并有调用loop方法,一样的,在ActivityThread实例的main方法中就已经调用了loop方法了,

public static void loop() {
    //首先会去获取looper实例
        final Looper me = myLooper();
        if (me == null) {
            //如果获取到的looper实例为null,会告诉你必须要先调用prepare方法 在当前线程中创建looper实例
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        if (me.mInLoop) {
            Slog.w(TAG, "Loop again would have the queued messages be executed"
                    + " before this one completed.");
        }

        me.mInLoop = true;
    //获取对应的MessageQueue实例
        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();

        // Allow overriding a threshold with a system prop. e.g.
        // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
        final int thresholdOverride =
                SystemProperties.getInt("log.looper."
                        + Process.myUid() + "."
                        + Thread.currentThread().getName()
                        + ".slow", 0);

        boolean slowDeliveryDetected = false;
        //进行遍历循环获取消息实体
        for (;;) {
            //获取消息队列中的消息实体
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            ......
            try {
                //调用Handler中的方法进行消息的分发
                msg.target.dispatchMessage(msg);
                if (observer != null) {
                    observer.messageDispatched(token, msg);
                }
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } catch (Exception exception) {
                if (observer != null) {
                    observer.dispatchingThrewException(token, msg, exception);
                }
                throw exception;
            } finally {
                ThreadLocalWorkSource.restore(origWorkSource);
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            ......
            msg.recycleUnchecked();
        }
    }

queue.next()就是通过链表中next的节点的移动去获取message消息实体

@UnsupportedAppUsage
    Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        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) {
                // Try to retrieve the next message.  Return if found.
                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) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        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 {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                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);
            }

            ......
        }
    }

将遍历获取到的消息再通过dispatchMessage去进行分发

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

到这里就看到前面更新ui时创建了一个Handler实例,并重写了其handlerMessage方法,这样在handlerMessage中进行消息的处理,ui的更新,在消息处理完后,还会对消息进行缓存处理,

@UnsupportedAppUsage
    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) {
            //MAX_POOL_SIZE 是50 就是说最大的缓存数量是50 超过50后就不会进行缓存处理
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

这样一个Handler消息处理流程就走完了。

总结:

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

推荐阅读更多精彩内容