标签:
我们都知道在主线程(即UI线程)要发送消息的话,只需要创建一个Handler即可,但你试下在子线程里面创建一个Handler,然后发送消息,你会发现程序报如下异常了,“can‘t create handler inside thread that has not called Looper.prepare();”
new Thread(new Runnable() { @Override public void run() { Handler mHandler = new Handler(); mHandler.sendEmptyMessage(0); } }).start();
我们来看看Looper的源码,其路径为\frameworks\base\core\java\android\os\Looper.java
/** Initialize the current thread as a looper. * This gives you a chance to create handlers that then reference * this looper, before actually starting the loop. Be sure to call * {@link #loop()} after calling this method, and end it by calling * {@link #quit()}. */ 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)); }首先,我们看到prepare方法里面创建了一个Looper,并把它保存到sThreadLocal,有对应的get方法取出该Looper,之后会用到;其次该方法每次都先判断sThreadLocal.get()是否为空,若不为空就抛出异常,确保每个线程只有一个Looper对象。
我们再来看看Looper的构造函数:
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
接下来看看Handler,我们知道Handler是用来发送消息以及处理消息的,先看看Handler是如何发送消息的,如何把该消息发到该线程对应Looper对象的MessageQueue队列上的?
一般我们都是直接new一个Handler,先看看Handler的源码:其路径为\frameworks\base\core\java\android\os\Handler.java,其构造函数:
public Handler() { this(null, false); } public Handler(Callback callback) { this(callback, false); } public Handler(Looper looper, Callback callback) { this(looper, callback, false); } 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(); 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; }源码里面提供了很多不同参数的构造函数,我一般都是直接new一个无参的,也就是以上代码的第一个构造函数,其间接会调用第四个构造函数,认真看下该方法,其中通过Looper.myLooper()方法获取到一个Looper对象mLooper,然后又获取到成员属性mQueue,我们在回过头来看看myLooper()方法:
public static Looper myLooper() { return sThreadLocal.get(); }很简单,就是把我们之前在当前线程new的一个Looper对象从sThreadLocal中给取出来了.至此,我们的Handler对象与Looper对象中的MessageQueue对象关联上了.
接下来看看如何发送消息的,API提供了很多send或post方法来发消息,不管用的哪个,最后都会调用enqueueMessage方法,看看该方法的具体实现:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }该方法其实就是把消息放到消息队列中,那么已经知道怎么发送消息了,保存消息的载体MessageQueue也有了,就只剩下Handler如何取消息跟处理消息了,我们回过头来看Looper.loop()方法:
/** * 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; // 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); } 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(); } }这里很重要的一点就是发送消息时MessageQueue跟这里取消息的MessageQueue是同一个(都是通过Looper的myLooper方法得到对应mQueue),至于具体如何关联上的,上面已经说明了。然后,就是一个无限死循环for(;;),不停的消息队列里取消息,当消息为空时,直接return。然后看msg.target.dispatchMessage(msg);这里调用了dispatchMessage(msg),这里我们看target是什么,认真的同学会发现上面的enqueueMessage方法里给target赋值了,msg.target = this; 这行代码表明,该target就是发送消息的Handler对象,在看看Handler里面dispatchMessage(msg)方法是如何具体实现的:
/** * 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); } }在这里,我们看到最后一行调用了handleMessage方法,该方法是空方法,具体由我们实现,就是我们在new一个Handler时都会重写的那个handleMessage方法.
private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case value: break; default: break; } }; };
标签:
原文地址:http://blog.csdn.net/hxf779159361/article/details/51329090