Looper

196 阅读2分钟

Looper消息循环

	// 线程Looper和线程消息队列存在关联
    // handler也和线程Looper绑定
    // 跨线程在于handler是线程共享
	private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
  * <pre>
  *  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();
  *      }
  *  }</pre>
 /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
        // 获取当前线程looper
        final Looper me = myLooper();
        // 线程looper空抛出异常, thread运行looper
        // loop循环需要prepare准备好loooper
        
        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循环从线程消息队列读取消息
        for (;;) {
        	// queue.next会阻塞
            // 防止消耗cpu
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            
            // Printer接口打印message处理前后
            // 可在此后计算消息执行消耗时间
            public interface Printer {
                /**
                 * Write a line of text to the output.  There is no need to terminate
                 * the given string with a newline.
                 */
                void println(String x);
			}

            // This must be in a local variable, in case a UI event sets the logger
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            // 消息target对象即handler对象, dispatchMessage消息
            /**
             * Handle system messages here.
             */
            // public void dispatchMessage(Message msg) {
            	  // runnable对象run
            //    if (msg.callback != null) {
            //        handleCallback(msg);
            //    } else {
            //        if (mCallback != null) {
            //            if (mCallback.handleMessage(msg)) {
            //                return;
            //            }
            //        }
            		  // override handleMessage回调
            //        handleMessage(msg);
            //    }
            // }
            
            
            
            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

            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();
        }
    }
 /*
                  void recycleUnchecked() {
                  // Mark the message as in use while it remains in the recycled object pool.
                  // Clear out all other details.
                  flags = FLAG_IN_USE;
                  what = 0;
                  arg1 = 0;
                  arg2 = 0;
                  obj = null;
                  replyTo = null;
                  sendingUid = -1;
                  when = 0;
                  target = null;
                  callback = null;
                  data = null;

                  synchronized (sPoolSync) {
                      if (sPoolSize < MAX_POOL_SIZE) {
                          next = sPool;
                          sPool = this;
                          sPoolSize++;
                      }
                  }
              }
            */