首页 > 代码库 > 什么是Handler(三)

什么是Handler(三)

1.Looper当中loop()方法的作用

2.什么是Message对象的Target

3.处理一个Message的方法

 

 1 public static void loop() {  //静态方法 2         final Looper me = myLooper(); //myLooper是根据已知的线程对象取出对应的Looper对象 3         if (me == null) { //判断取出的Looper对象是否为空 4             throw new RuntimeException("No Looper; Looper.prepare() wasn‘t called on this thread."); 5         } 6         final MessageQueue queue = me.mQueue; //取出Looper的消息队列 7  8         // Make sure the identity of this thread is that of the local process, 9         // and keep track of what that identity token actually is.10         Binder.clearCallingIdentity();11         final long ident = Binder.clearCallingIdentity();12 13         for (;;) {  //此循环是不停的从消息队列中取出消息,如果没有值就会阻塞14             Message msg = queue.next(); // might block 15             if (msg == null) {16                 // No message indicates that the message queue is quitting.17                 return;18             }19 20             // This must be in a local variable, in case a UI event sets the logger21             Printer logging = me.mLogging;22             if (logging != null) {23                 logging.println(">>>>> Dispatching to " + msg.target + " " +24                         msg.callback + ": " + msg.what);25             }26 27             msg.target.dispatchMessage(msg);//查看Message.java源码, 28             //一个Handler对应一个looper对象,一个looper对应一个MessageQueue对象,使用Handler生成Message, 所生成的Message对象的target属性, 就是该Handler对象29            //查看Handler的dispatchMessage方法, 得知用handlerMessage处理消息30 31             if (logging != null) {32                 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);33             }34 35             // Make sure that during the course of dispatching the36             // identity of the thread wasn‘t corrupted.37             final long newIdent = Binder.clearCallingIdentity();38             if (ident != newIdent) {39                 Log.wtf(TAG, "Thread identity changed from 0x"40                         + Long.toHexString(ident) + " to 0x"41                         + Long.toHexString(newIdent) + " while dispatching to "42                         + msg.target.getClass().getName() + " "43                         + msg.callback + " what=" + msg.what);44             }45 46             msg.recycle();47         }48     }    

 

什么是Handler(三)