Thread thread = new Thread() { public void run() { //子线程中发送消息给主线程 Message msg = new Message(); msg.what = 200; msg.obj = param; msg.arg1 = 3; handler.sendMessage(msg); }; }; Handler handler = new Handler() { public void handleMessage(Message msg) { //主线程接收到消息,更新UI }; };
public Handler() { this(null, false); } 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; }
final MessageQueue mQueue; //消息队列(链表结构,下面会分析到) final Looper mLooper; //可理解为消息处理器而MessageQueue是Looper的成员属性。
public boolean sendMessageAtTime(Message msg, long uptimeMillis) { MessageQueue queue = mQueue; if (queue == null) {} return enqueueMessage(queue, msg, uptimeMillis); } private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { //注意这一行,将Handler自已赋值给了Message的target属性,下面的析中会用到 msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
boolean enqueueMessage(Message msg, long when) { synchronized (this) { 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; }
class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { // process incoming messages here } }; Looper.loop(); } }
Looper.prepare(); Looper.loop();这里面大有学问,在继续往下分析之前,我们再大胆猜测UI线程加载Activity的过程的前后也调用了这两个方法。
public static void prepare() { prepare(true); } //设置当前线程私有的Looper对象 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对象 static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); //获取当前线程私有的Looper对象 public static Looper myLooper() { return sThreadLocal.get(); }
/** * Run the message queue in this thread. Be sure to call * {@link #quit()} to end the 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; } msg.target.dispatchMessage(msg); msg.recycle(); } }
/** * 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); } }
在多线程的环境中,主线程和子线程之间交互是通过一个链表结构的消息队列(MessageQueue),子线程只管往里面放入消息(Message),消息是按时间的先后顺序排列的,主线程用一个消息处理器(Looper)不断地逐个逐个地处理掉消息。
@容新华技术博客 - http://blog.csdn.net/rongxinhua - 原创文章,转载请注明出处
【Android】从源码中探讨Handler机制,布布扣,bubuko.com
原文:http://blog.csdn.net/rongxinhua/article/details/20576185