当我们new一个Handler的时候调用了它的构造函数
public Handler() { .... mLooper = Looper.myLooper();//mLooper 是一个Loop if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue;//mQueue是一个MessageQueue,也就是我们要找的消息队列, mCallback = null;//是一个Callback,是Handler的内部接口, }查看Loop的文档:
class LooperThread extends Thread { * public Handler mHandler; * * public void run() { * Looper.prepare();//在线程里调用prepare方法 * * mHandler = new Handler() { * public void handleMessage(Message msg) { * // process incoming messages here * } * }; * * Looper.loop();//循环处理消息 * } * }来看看prepare方法:
public static final void prepare() { if (sThreadLocal.get() != null) {//sThreadLocal为ThreadLocal类,即线程局部变量,含线程自己的独立副本,使线程可以独立地改变自己的副本 throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper());//把Looper对象放入线程局部变量中,使得Looper()对象与线程关联了起来 }来看看Looper的构造函数,构造函数中创建了消息队列,并记录当前线程,使当前线程与消息队列相关
private Looper() { mQueue = new MessageQueue();//创建消息队列, mRun = true; mThread = Thread.currentThread();//当前线程 }在SDk我们给的例子知道,先调用prepare,然后再new Handler实例,然后再调用loop方法,
public static final Looper myLooper() { return (Looper)sThreadLocal.get(); }myLooper方法就是从刚才的线程局部变量中拿出和线程相关的Looper,然后把Looper的消息队列都赋给Hanlder的消息队列,这样,
public static final void loop() { Looper me = myLooper();//也是获得线程局部变量中的Looper MessageQueue queue = me.mQueue;//线程的消息队列 while (true) {//循环 Message msg = queue.next(); // might block//线程消息队列是一个链表,含有它的下一条消息 //if (!me.mRun) { // break; //} if (msg != null) { if (msg.target == null) {//把target设置为null意味着退出消息循环(target为Handler类),以后可以使用这种方式来退出消息循环 // No target is a magic identifier for the quit message. return; } if (me.mLogging!= null) me.mLogging.println( ">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what ); msg.target.dispatchMessage(msg);//调用Handler的分发dispatchMessage方法 if (me.mLogging!= null) me.mLogging.println( "<<<<< Finished to " + msg.target + " " + msg.callback); msg.recycle(); } } }来看看dispatchMessage
public void dispatchMessage(Message msg) { if (msg.callback != null) {//消息中的callback为Runnable类,不空时调用run方法 handleCallback(msg); } else { if (mCallback != null) {//mCallback为Handler类的内部接口Callback,有handleMessage一个方法,如果不为空的话则执行该Callback的handleMessage方法,该方法由用户去创建 if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg);//如果Message的callback不为空,Handler的Callback不为空才会执行该方法,该方法也是SDK推荐的在创建Handler时必须实现的方法,在该方法中实行所要的操作 } }由以上分析我们知道,Handler可以3种形式的方法来处理消息,
然后用debug模式打开模拟器,在debug模式下可以看到如下的信息:
public static final void main(String[] args) { SamplingProfilerIntegration.start(); Process.setArgV0("<pre-initialized>"); Looper.prepareMainLooper();//prepare ActivityThread thread = new ActivityThread(); thread.attach(false); Looper.loop();//loop if (Process.supportsProcesses()) { throw new RuntimeException("Main thread loop unexpectedly exited"); } thread.detach(); String name = (thread.mInitialApplication != null) ? thread.mInitialApplication.getPackageName() : "<unknown>"; Slog.i(TAG, "Main thread of " + name + " is now exiting"); }因此UI主线程才会有自己的消息队列。
HandlerThread handlerThread = new HandlerThread("handler_thread"); //在使用HandlerThread的getLooper()方法之前,必须先调用该类的//start(); handlerThread.start(); MyHandler myHandler = new MyHandler(handlerThread.getLooper());//传入新的Loop到Handler里边HandlerThread继承了Thread方法,因而调用start方法会启动一个新的线程,我们来看看run中的实现
public void run() { mTid = Process.myTid(); Looper.prepare();// synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop();// mTid = -1; }在run中用到了prepare --' loop 因而可以在新的线程中创建新的消息队列。