美文网首页
Android中Handler机制浅谈

Android中Handler机制浅谈

作者: codingwz | 来源:发表于2017-07-18 13:14 被阅读0次

Android中的Handler一般是用于异步任务,和Handler相关的一些概念有Looper,MessageQueue,下面先通过一张图来展示三者只之间的关系。


MessageQueue主要是维护消息队列,Handler主要是消息的发送和处理,Looper扮演着管理者这么一个角色,由它来维护这个流程的正常执行。
首先来分析一下这个管理者Looper,它是一个线程独享的变量,所以再此之间还得先了解一个概念ThreadLocal,这是Android系统提供的一个类,用于实现线程独享。

  • ThreadLocal的使用 。
    //存储 ThreadLocal<Integer> tl = new ThreadLocal<>(); Integer var = new Integer(1); tl.set(var); //使用。在哪个线程中调用,就会使用哪个线程中的备份。 Integer local = tl.get();

  • ThreadLocal原理。
    在使用ThreadLocal时主要会用到两个方法,set()和get()方法。直接从源码看起。
    public void set(T value) {
    Thread currentThread = Thread.currentThread();
    Values values = values(currentThread);
    if (values == null) {
    values = initializeValues(currentThread);
    }
    values.put(this, value);
    }
    set的代码很简单,首先获得当前线程,再获得一个Values变量,最后是调用了values.put(this,value)方法。
    public T get() {
    // Optimized for the fast path.
    Thread currentThread = Thread.currentThread();
    Values values = values(currentThread);
    if (values != null) {
    Object[] table = values.table;
    int index = hash & values.mask;
    if (this.reference == table[index]) {
    return (T) table[index + 1];
    }
    } else {
    values = initializeValues(currentThread);
    }

      return (T) values.getAfterMiss(this);
    }
    

同样get的逻辑也很清楚,首先获得当前线程,然后获得一个Values变量,通过values中的table属性来获得所需的值。
set和get中都出现了一个类Value,接下来看一下Value这个类。Values是ThreadLocal的静态内部类,我们主要关注一下其中的table属性,put和value方法。
Values values(Thread current) {
return current.localValues;
}
values方法非常简单,就是获得当前线程的localValues变量。而localValues变量就是Thread类中的一个属性。
Thread { ThreadLocal.Values localValues; } 想必看到这就明白为什么在不同线程环境下能够获得各自线程的本地变量了。因为实质上就是在每个Thread内部存储了一个本地变量,通过空间来换时间达到同步的作用。
static class Values {
/**
* Map entries. Contains alternating keys (ThreadLocal) and values.
* The length is always a power of 2.
*/
private Object[] table;

      void put(ThreadLocal<?> key, Object value) {
        cleanUp();

        // Keep track of first tombstone. That's where we want to go back
        // and add an entry if necessary.
        int firstTombstone = -1;

        for (int index = key.hash & mask;; index = next(index)) {
            Object k = table[index];

            if (k == key.reference) {
                // Replace existing entry.
                table[index + 1] = value;
                return;
            }

            if (k == null) {
                if (firstTombstone == -1) {
                    // Fill in null slot.
                    table[index] = key.reference;
                    table[index + 1] = value;
                    size++;
                    return;
                }

                // Go back and replace first tombstone.
                table[firstTombstone] = key.reference;
                table[firstTombstone + 1] = value;
                tombstones--;
                size++;
                return;
            }

            // Remember first tombstone.
            if (firstTombstone == -1 && k == TOMBSTONE) {
                firstTombstone = index;
            }
        }
      }
  }

table变量很简单,就是一个Object数组,用于存储所需的值。接下来分析一下put方法。主体就是一个for循环,遍历所有的index,可以把index当做映射关系中的键,通过对应的键最终取到需要的值。
private static AtomicInteger hashCounter = new AtomicInteger(0); private final int hash = hashCounter.getAndAdd(0x61c88647 * 2); //Weak reference to this thread local instance. private final Reference<ThreadLocal<T>> reference = new WeakReference<ThreadLocal<T>>(this);
把table作为键值的存储结构,index下标所对应的为键,index + 1下标所对应的为实际存储的值。
如果k已经存在,就直接更新它的值。如果k不存在,就把key.reference存入table中的index下标位置,把值存在table中index + 1的下标位置。

  • Looper-消息的管理者
    在理解了ThreadLocal的原理之后,就可以明白Looper为什么是线程独享的了。一般的使用方法如下:
    Looper.prepare(); . . . Looper.loop();
    handler必须得在这个代码块中间初始化。
    首先看看prepare方法中的代码:
    public static void prepare() {
    prepare(true);
    }
    就调用了一个重载方法:
    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));
    }
    sThreadLoca就是Looper内部的ThreadLocal属性。首先通过get方法获得Looper变量,如果不为空,就会报错,也就是Looper.prepare方法为什么只能调用一次的原因。如果不为空,就调用set方法,把Looper变量存储ThreadLocal的table中。
    接下来分析Looper.loop()方法的核心代码:
    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(); // might block
    if (msg == null) {
    // No message indicates that the message queue is quitting.
    return;
    }
    final long traceTag = me.mTraceTag;
    try {
    msg.target.dispatchMessage(msg);
    } finally {
    if (traceTag != 0) {
    Trace.traceEnd(traceTag);
    }
    }
    }
    }
    首先获得Looper变量me,myLooper方法很简单,如下:
    public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
    }
    就是通过sThreadLocal的get方法获得当前线程的Looper变量。
    然判断me是否为空,为空就报错,也就是说loop方法必须在prepare方法之后调用。
    接着拿到MessageQueue对象,这个对象是Looper的内部属性,在构造函数中进行初始化。
    随后就是for循环,这是一个无限循环体,退出的唯一条件就是获取到的消息为null。
    通过queue去拿到需要处理的消息(这个消息是通过handler发出的),然后注意next方法是会阻塞的,也就是如果没有消息,程序会一直停留在这一行代码。
    当取得消息不为空,就执行msg.target.dispatchMessage(msg),msg.target其实就是handler,handler中有一个方法dispatchMessage(Message msg),这样就把消息的处理交到了handler的手里,完成了Looper的交接任务。

  • MessageQueue-消息队列
    MessageQueue主要就是维持一个消息队列。主要的方法就是enqueueMessage和next。
    boolean enqueueMessage(Message msg, long when) {
    synchronized (this) {
    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;
    }
    

mMessages是MessageQueue中的属性,它指向消息队列的头部,即下一刻需要处理的消息。这里第一个if判断需要添加新的头部。条件1是当前队列为空,条件2是当前加入的消息为立刻处理,条件3是当前加入的消息比队列首部的消息优先级高(通过消息需要触发时的时间先后来判断)。三者任意一个满足,就需要把当前消息作为头部加入消息队列。
如果不满足,则进入else部分。通过一个for循环,把消息插入到队列的中间,具体的位置是根据优先级来判断。
这样消息的插入就完成了。接下来分析如何取出消息(核心代码):
Message next() {
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
synchronized (this) {
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
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;
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;
            }              
    }
  }

方法的主体就是一个for无限循环体,这也就解释了为什么在Looper中调用MessageQueue的next方法会阻塞了。now是系统当前的时间,msg即当前的头部消息,如果不为空,且msg.when 大于 now,即说明当前消息还没有到需要处理的时候,那么让线程挂起。等待nextPollTimeoutMillis 时间后,唤醒线程继续处理消息。
如果消息已经可以处理,那么移动头部引用mMessage为msg的下一个,然后返回当前消息。
至此,消息的添加和取出的逻辑已经分析完毕。

  • Handler-消息的处理者
    首先看handler的使用代码:
    public static Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
    //具体逻辑处理
    }
    };
    一般都是实现一个匿名内部类,然后重写handleMessage方法。下面分析一下,handler的构造函数进行了哪些操作:
    public Handler(Callback callback, boolean async) {
    mLooper = Looper.myLooper();
    if (mLooper == null) {
    throw new RuntimeException(
    "Can't create handler inside thread that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
    }
    Handler有很多重载的构造函数,但最后都会调用此方法。首先获得当前所关联的Looper,这也就是为什么handler的初始化必须在Looper.prepare()之后了。随后获取当前的消息队列。
    接下来分析一下dispatchMessage方法,想必大家还记得在Looper中取到消息后调用了msg.target,dispatchMessage(),这里就分析一下消息是怎么处理的:
    public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
    handleCallback(msg);
    } else {
    if (mCallback != null) {
    if (mCallback.handleMessage(msg)) {
    return;
    }
    }
    handleMessage(msg);
    }
    }
    首先是判断msg.callback,如果 不为空则直接调用handleCallback方法。而msg的callback其实就是一个Runnable对象,handleCallback方法也就是简单的调用了Runnable的run方法。
    private static void handleCallback(Message message) {
    message.callback.run();
    }
    如果msg.callback为空,则判断mCallback是否为空,而mCallback就是Handler的一个内部接口:
    public interface Callback {
    public boolean handleMessage(Message msg);
    }
    这个接口为用户提供了另外一种实现handler的方法,就是实现一个Callback,最为参数传入Handler的构造函数,然后具体的消息处理逻辑就在Callback的handleMessage方法中去实现,代码实例如下:
    public static Handler mHandler = new Handler(new Handler.Callback(){
    @Override
    public void handleMessage(Message msg) {
    //具体逻辑处理
    }
    });
    再回到dispatchMessage方法中,如果mCallback.handleMessage(msg)返回了true,那么消息处理就结束了,如果返回了false,或者mCallback为空,则就会调用Handler的handleMessage(msg)方法,该方法默认是空方法,没有任何的操作。
    消息的处理流程理清楚后再来看看消息的发送,主要有post和sendMessage两大类方法。
    post方法主要是通过Runnable,设置为msg.callback。下边来看一个post方法:
    public final boolean post(Runnable r)
    {
    return sendMessageDelayed(getPostMessage(r), 0);
    }
    跟踪一下sendMessageDelayed和getPostMessage方法:
    private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
    }

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

这两个方法很简单,最终会进入sendMessageAtTime方法:
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);
}
这个方法同样逻辑非常简单,那么再进入enqueueMessage方法:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
这里终于出现了msg.target = this,原来handler是在发送消息的时候关联到具体的msg上的。
最后调用了queue的enqueueMessage方法,这个方法已经在上边分析过了。
下边来分析一下sendMessage方法:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}

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

同样,最终还是会调用sendMessageAtTime这个方法。

  • 注意事项
    1 Handler在哪个线程进行的初始化,那么最终消息的处理线程就一定是这个线程。
    2 Handler一定要在Looper初始化以后才能进行初始化。
    3 主线程默认已经调用了Looper.loop(),所以才可以直接实例化Handler,若是在其他线程需要实例化Handler,那么一定要先调用Looper.loop(),为当前线程初始化自己的Looper对象。

相关文章

网友评论

      本文标题:Android中Handler机制浅谈

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