Handler的构造函数有四个,在构造函数中获取了Looper对象和MessageQueue消息队列
每个Handler对应一个Looper对象和MessageQueue对象
让Handler处理消息有两种方法:
向Handler构造方法中传入Handler.Callback对象,并实现Handler.Callback的handleMessage方法无需向Hanlder的构造函数传入Handler.Callback对象,但是需要重写Handler本身的handleMessage方法通过上述代码可以看出Handler发送消息有多种方式,但是最后都会调用sendMessageAtTime()方法,sendMessageAtTime()最后会调用enqueueMessage()方法,该方法会设置msg.target为当前的handler对象,并将消息添加到队列中。
所以创建Handler对象时只是得到了当前线程的Looper对象和MessageQueue队列,在handler对象发送消息的时候才会将设置target并且将消息添加到消息队列中。
Android在启动运行主线程main()方法的时候调用了Looper中的prepare()和looper()方法,为主线程事先创建了Looper对象并启动了消息循环。
prepare()方法流程
public static void prepare() { prepare(true); } private static void prepare(boolean quitAllowed) { //证了一个线程中只有一个Looper实例 if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } //通过ThreadLocal实现Looper实例和线程的绑定 sThreadLocal.set(new Looper(quitAllowed)); } //构造方法实例化当前的MessageQueue和当前线程 private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); } public static MessageQueue myQueue() { return myLooper().mQueue; }looper()方法流程
public static void loop() { final Looper me = myLooper(); //获取looper并且不能为空 if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) { //for循环通过MessageQueue中的next()方法获取消息队列中的消息 Message msg = queue.next(); // might block if (msg == null) { return; } Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } //调用绑定的target也就是消息的handler对象执行对消息的处理 msg.target.dispatchMessage(msg); if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } // 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中的dispatchMessage()方法如下
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }在上述代码中可以看到消息最终被handler对象的handleMessage()方法处理了。
因为子线程使我们手动创建的,并没有Looper和MessageQueue,所以需要我们自己创建。 在子线程中使用Handler需要三步
1.调用Looper的prepare()方法,为当前线程创建looper对象,然后将looper对象与当前线程绑定。在创建looper对象的时候会同时创建MessageQueue消息队列对象,这样Looper对象有了,MessageQueue对象也有了。然后重写handler对象的handleMessage()方法或者传入Handler.Callback对象重写其中的handleMessage()方法。调用Looper的looper()方法让循环启动起来通过队列中的next()方法获取消息然后调用handleMessage()处理消息。新闻热点
疑难解答