Potato icon indicating copy to clipboard operation
Potato copied to clipboard

Handler:Android Message Model

Open yunshuipiao opened this issue 5 years ago • 0 comments

Handler:Android Message Model

[TOC]

依旧由 ActivityThread 的 main() 函数讲起。该函数作为应用程序运行的初始函数,在其中做了很多的初始化工作,比如 handler,这篇文章就从源码角度分析 Android 中的通信机制, Handler。

// ActivityThread.java
public static void main(String[] args) {
  	// UI 线程初始化 loop 
  	Looper.prepareMainLooper();
    if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
  	// 开启 loop 循环,接收并处理消息
  	Looper.loop();
}

在 main 函数中主要做的是初始化工作, 下面从 Looper 开始进行分析。

Looper

Looper 类的作用是在一个线程中创建消息循环,大部分的都交由 handler 来处理。

其主要的属性如下:

private static final String TAG = "Looper";

// sThreadLocal.get() will return null unless you've called prepare().
// 保存不同线程的 looper 对象
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper;  // guarded by Looper.class

// 消息队列,保存消息
final MessageQueue mQueue;
final Thread mThread;
public static void prepareMainLooper() {
    prepare(false);
  	// 同步方法,保证线程只能有一个 looper 实例
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
      	// 获取 UI 线程的 looper 
        sMainLooper = myLooper();
    }
}

private static void prepare(boolean quitAllowed) {
  // 保证只能有一个 Looper 实例
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
  			// 同时完成 MessageQueue 和 thread 的创建
        sThreadLocal.set(new Looper(quitAllowed));
    }

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

 public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
 }

ThreadLocal

这里需要提一下 ThreadLocal:该类可以在不同线程存取不同的值,做到线程独有。看一下其 get() 方法。

// 获取当前线程保存的值
public T get() {
  	// 当前线程,这时是主线程
    Thread t = Thread.currentThread();
  	// 获取线程中保存的 map
    ThreadLocalMap map = getMap(t);
    if (map != null) {
      	// 获取 Entity 对象, 见后续
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

// set 方法
public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

上面同时有 get/set 方法,对照看可以很简单的理解。其中 getMap() 获取了线程中的 ThreadLocalMap 对象。

// 自定义的 map,用户维护线程局部变量
static class ThreadLocalMap {
    static class Entry extends WeakReference<ThreadLocal<?>> {
        /** The value associated with this ThreadLocal. */
        Object value;
				// 实体,ThreadLocal 为 key。
        Entry(ThreadLocal<?> k, Object v) {
            super(k);
            value = v;
        }
    }

有了上述理解,可以知道 ThreadLocal 可以针对不同线程,保存不同的值,这里就线程独有的 looper 对象。

/**
 * Run the message queue in this thread. Be sure to call
 * {@link #quit()} to end the loop.
 * 开启本线程的消息循环,结束时调用 quit 提出。
 */
public static void loop() {
    final Looper me = myLooper();
  	// 这里有个点。因为主线程在 main 函数中就创建并保存了 looper。如果是在自线程,必须要首先调用下面注释汇总的方法,创建 looper, 否则程序会崩溃。
    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(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }
      ...
        try {
          	// 分发处理消息
            msg.target.dispatchMessage(msg);
        } finally {
        }
        msg.recycleUnchecked();
    }
}

上面的工作主要是在当前线程开启了无限循环, 不断从 MessageQueue 中获取消息,然后进行 target 分发。

这里的 target 就是 handler。因为 Handler 并没有直接绑定在 Looper 中。好处在于可以创建多个 Handler 。

MessageQueue

Message next() {
    for (;;) {
        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) {
              	// 绑定 handler
                // 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;
            }
    }
}

这里通过循环不断的取出消息,让后等待消息分发时间到之后将消息分发出去,从而建立消息循环。

Message 的对象池和复用

官方建议,在使用 Message 时最好使用 Message.obtain() 和 Message.obtainMessage(), 从一个可以回收的对象池中获取。

public static Message obtain() {
    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();
}

维护一个 对象池来复用 Message。

消息从哪里来,下面就开始分析 Handler 发送和处理消息。

Handler

public Handler() {
    this(null, false);
}
public Handler(Callback callback) {
        this(callback, false);
}
public Handler(Looper looper) {
        this(looper, null, false);
    }
public Handler(Looper looper, Callback callback) {
        this(looper, callback, false);
    }
public Handler(boolean async) {
        this(null, async);
    }

这里主要由四个构造方法,分别用于初始化 Handler 中的 looper, queue, callback 和 mAsynchronous。

public Handler(Callback callback, boolean async) {
  	// 判断可能存在内存泄漏的标记
    if (FIND_POTENTIAL_LEAKS) {
        final Class<? extends Handler> klass = getClass();
        if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                (klass.getModifiers() & Modifier.STATIC) == 0) {
            Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                klass.getCanonicalName());
        }
    }

    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread " + Thread.currentThread()
                    + " that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}
// 常用方法一
public final boolean post(Runnable r)
{
   return  sendMessageDelayed(getPostMessage(r), 0);
}

private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
  			// 消息的 callback 初始化
        m.callback = r;
        return m;
}
// 常用方法二
public final boolean sendMessage(Message msg)
{
        return sendMessageDelayed(msg, 0);
    }


// 最终调用
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
  			// handler 赋值给 target,后续使用 handler 处理
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
boolean enqueueMessage(Message msg, long when) {
		...
    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;
      	// 新消息
        if (p == null || when == 0 || when < p.when) {
            // 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;
}

当有消息需要处理时,handler 会调用 下面方法:

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

现在在上述提到的知识点中,还有一个 异步消息的概念。

异步消息

MessageQueue 中发送的消息已经按时间顺序排好,那么如果要让消息有优先级区别呢.

public int postSyncBarrier() {
    return postSyncBarrier(SystemClock.uptimeMillis());
}

private int postSyncBarrier(long when) {
    // Enqueue a new sync barrier token.
    // We don't need to wake the queue because the purpose of a barrier is to stall it.
    synchronized (this) {
        final int token = mNextBarrierToken++;
        final Message msg = Message.obtain();
        msg.markInUse();
        msg.when = when;
        msg.arg1 = token;

        Message prev = null;
        Message p = mMessages;
        if (when != 0) {
            while (p != null && p.when <= when) {
                prev = p;
                p = p.next;
            }
        }
        if (prev != null) { // invariant: p == prev.next
            msg.next = p;
            prev.next = msg;
        } else {
            msg.next = p;
            mMessages = msg;
        }
        return token;
    }
}

看起来这个方法也没有什么特别的地方,唯一的区别就是消息没有target,也就是没有Handler对象,MessageQueue在执行next方法时就会走到if (msg != null && msg.target == null)中,此时它会忽略其间所有的同步消息,直到找到一个异步消息并开始执行,这个做法称之为同步屏障。调用此方法后可以得到一个token值,可以通过这个值取消屏障。然后我们就可以向MessageQueue发送一个异步消息,优先执行此事件了。MessageQueue#postSyncBarrier通常需要与MessageQueue#removeSyncBarrier成对使用,否则就再也接收不到同步消息了。目前,这个方法被标记为HIDE,在API层面无法调用。

同步屏障的应用

Android 应用框架中为了更好的响应 UI 刷新,在 ViewRootImpl.scheduleTraversals 中使用了同步屏障, 为了让 mTravelsalRunnable 更快的执行。

void scheduleTraversals() {
    if (!mTraversalScheduled) {
        mTraversalScheduled = true;
        mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
        mChoreographer.postCallback(
                Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
        if (!mUnbufferedInputDispatch) {
            scheduleConsumeBatchedInput();
        }
        notifyRendererOfFramePending();
        pokeDrawLockIfNeeded();
    }
}

总结

这篇文章讲了 Handler 机制,主要涉及 Looper, MessageQueue, Message 和 Handler 之间的关系。

后续所有的子线程回调主线程更新 UI 的操作都是基于此实现,非常重要。

yunshuipiao avatar May 19 '19 12:05 yunshuipiao