一、问题描写叙述:
利用Handler可以轻松的将任务发送到Handler所在的线程进行处理。Android中用到最多的是将在线程中訪问网络获取到的数据通过Handler发送到UI线程进行UI操作。那么Handler的实现原理是什么呢。
二、分析:
要实现Handler,须要有例如以下几个类的辅助
Message:能够存储信息的消息体
Handler:负责分发消息
MessageQueue:负责存储消息
Looper:负责对消息进行轮询处理
(1)Handler发送消息
Handler中的sendMessage,sendMessageDelayed,post,postDelayed终于都是调用的sendMessageAtTime()
sendMessageAtTime里面的逻辑仅仅是通过enqueueMessage()将消息放到MessageQueue中。
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);}
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);}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {msg.target = this;if (mAsynchronous) {msg.setAsynchronous(true);}return queue.enqueueMessage(msg, uptimeMillis);}
(2)MessageQueue加入消息
跳转到MessageQueue中查看enqueueMessage方法,当中的一段代码。这里是通过链表的形式将message加入到了message链表后
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.nextprev.next = msg;(3)Looper无限轮询消息
所以Handler的作用就是将message加入到MessageQueue中,并没有运行对Message进行处理。
对Message进行处理的是Looper类,看Looper类钟的looper方法,里面开启了一个无线循环for(; ;)。在无线循环中。queue.next会进入堵塞状态。直到queue中有新的Message加入。然后对msg进行处理,msg.target.dispatch(msg)
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;// 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 blockif (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 loggerPrinter logging = me.mLogging;if (logging != null) {logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what);}msg.target.dispatchMessage(msg);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();}}
转到Handler的dispatch方法,能够看到,会先推断msg中是否有callback,callback是Message中的一个Runnable成员,这个推断是区分Handler的post方法和send方法的,post方法的參数是Runnable,send的參数是msg,尽管终于都是转换成message的。
假设callback为null,就调用handleMessage方法,这种方法就是我们创建Handler的时候须要重写的方法。
callback不为空的时候直接调用了runnable.run方法运行runnable中的逻辑。
/** * Handle system messages here. */public void dispatchMessage(Message msg) {if (msg.callback != null) {handleCallback(msg);} else {if (mCallback != null) {if (mCallback.handleMessage(msg)) {return;} }handleMessage(msg);}}
三、常见问题
(1)为什么Handler使用的时候一定要调用Looper.prepare()和Looper.loop()方法?
从上面的分析来看,Handler的使用须要MessageQueue存储Message,还须要Looper对Message进行无线轮询取出。然后进行处理。所以Handler的使用时离不开MessageQueue和Looper的。
我们来看Handler的构造方法里面有没有对Looper和MessageQueue进行初始化。先来看无參数的Handler构造方法
public Handler() {this(null, false);}跳转到两个參数的构造方法,注意mLooper=Looper.myLooper();将Handler的成员变量mLooper进行了赋值。用得到的Looper对象也对mQueue进行了赋值mQueue=mLooper.mQueue;
public Handler(Callback callback, boolean async) {if (FIND_POTENTIAL_LEAKS) {final Class 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 that has not called Looper.prepare()");}mQueue = mLooper.mQueue;mCallback = callback;mAsynchronous = async;}跳转到Looper的myLooper方法,他返回了sThreadLocal.get();
public static @Nullable Looper myLooper() {return sThreadLocal.get();}我们再看看Looper的prepare方法。在里面对sThreadLocal的set了一个Looper对象,将looper对象存储到了sThreadLocal中。所以要是我们在使用Handler之前不调用Looper.prepare对sThreadLocal设置一个looper对象,那么在调用初始化Handler的时候,调用Looper.myLooper得到的mLooper就为NULL了。
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));}调用了looper.prepare之后还须要记得调用Looper.loop()开启对消息的调用。
(2)为什么在Activity中不须要调用Looper.prepare和loop
由于在ActivityThread的源代码中已经调用了prepare和looper方法了。所以我们在Activity中不须要调用就能够直接使用。