对于Android开发者来说,Handler是我们经常使用的一个异步线程的工具,它一般是配合Looper,Message来进行的,接下来我们将从源码的角度来看看它是怎么进行异步通讯的。
######(1)接收消息
Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case JUMP_TO_MAIN_ACTIVITY: startPage(getContext(), MainActivity.class); break; case JUMP_TO_GUID_ACTIVITY: startPage(getContext(), GuideActivity.class); break; } } };注意:重写的handleMessage(Message msg)方法传回来的msg 就是子线程通过Handler发过来的消息,我们将在UI线程更新UI的操作。
点击进入Handler的源码发现,Handler初始化时也初始化了以下的实例:
public Handler(boolean async) { this(null, async); } 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();//得到了Looper的实例 if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue;//得到了MessageQueue的实例 mCallback = callback; mAsynchronous = async; } //从本地线程变量sThreadLocal,获取一个Looper对象 public static @Nullable Looper myLooper() { return sThreadLocal.get(); } //获取主线程的Looper 实例 public static Looper getMainLooper() { synchronized (Looper.class) { return sMainLooper; } }注意:在非主线中实例化Handler会抛异常,如下: new Thread(new Runnable() { @Override public void run () { mHandler1 = new Handler(); } }).start(); handleMessage(msg)这个方法就是文章开始,初始化Handler的时候复写的方法。 这样就会抛出异常:
"Can't create handler inside thread that has not called Looper.prepare()");怎么修改才能不抛出异常呢?得改成这样:
new Thread(new Runnable() { @Override public void run () { Looper.prepare(); mHandler1 = new Handler(); Looper.loop(); } }). start();没错,加上Looper.prepare()和Looper.loop()就不会报错啦!
Looper 在线程中都会先调用Looper.prepare()和Looper.loop() 两个方法。在主线程中Activity 中已经自己调用,所以在子线程使用时得自己写。
那么我们去看看这两个方法到底做了啥:
prepare ()方法就是往sThreadLocal添加一个Looper对象嘛。那么sThreadLocal又是何方神圣呢?
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();这是本地的一个ThreadLocal,专门存放Looper对象的一个集合。
注意:在当前线程中只能创建一个Looper实例和一个对应的MessageQueue, 否则会抛出异常:
"Only one Looper may be created per thread”看源码:
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 block if (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 logger Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } //注意:这里是一个handler msg.target.dispatchMessage(msg); handler里还有好几个post和send的方法最终都调用的sendMessageAtTime()方法,看看sendMessageAtTime()方法里有啥? 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(); } }(1)获取一个Looper对象,和一个messageQueue对象, (2)for (;;) {}死循环的遍历messageQueue获取message,每个message.target就是一个handler对象,所以说每个handler携带了发送消息的handler, (3)handler调用dispatchMessage(msg),发送的住线程中
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }handleMessage(msg)这个方法就是文章开始,初始化Handler的时候复写的方法。 ######(2)发送消息
Message msg = Message.obtain(); msg.obj = data; msg.what = 0; // 发送这个消息到消息队列中 (1) mHandler.sendMessage(msg); (2) mHandler.sendEmptyMessageDelayed(2000, 0); (3) mHandler.post(new Runnable() { @Override public void run() { // 在Post中操作UI组件ImageView } (4) runOnUiThread(); .......有好几个方法都可以把非UI线程的数据发送到UI线程处理。看看具体的源码:
public final boolean post(Runnable r) { return sendMessageDelayed(getPostMessage(r), 0); } public final boolean postAtTime(Runnable r, long uptimeMillis) { return sendMessageAtTime(getPostMessage(r), uptimeMillis); } public final boolean postAtTime(Runnable r, Object token, long uptimeMillis) { return sendMessageAtTime(getPostMessage(r, token), uptimeMillis); } public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }handler里还有好几个post和send的方法最终都调用的sendMessageAtTime()方法,看看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); }handler里的 enqueueMessage 方法里又有啥呢?
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }这里调用的居然是MessageQueue里的 enqueueMessage()方法,那这里面又有啥奥秘呢?
boolean enqueueMessage(Message msg, long when) { if (msg.target == null) { throw new IllegalArgumentException("Message must have a target."); } if (msg.isInUse()) { throw new IllegalStateException(msg + " This message is already in use."); } 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; }msg.target就是handler对象,先判断是否为空,在判断是否被使用,然后在把当前的message对象插入消息队列,消息队列的消息是按待处理时间排序的。这样在messageQueue中则有了消息的对象。looper.loop()方法循环的时候就能找到message,则消息就能传入主线程,进而在非UI线程改变UI的操作。
Looper负责的是创建一个MessageQueue对象,然后进入到一个无限循环体中不断取出消息,而这些消息都是由一个或者多个Handler进行创建处理。
Messages的源码比较简单,没有分析。
怎么样?是否对Handler,Message,MessageQueue,Looper关系更加了解一点呢?不了解也没有关系,多看几遍源码就会明白了,要相信聪明的自己。
有啥不妥的地方,欢迎大家留言指教!
参考链接: http://www.cloudchou.com/android/post-388.html http://www.jianshu.com/p/36a978b6cacc