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所属线程必须和当前执行任务的线程保持一致。

你可能感兴趣的:(Handler源码分析)