Android源码解析--Looper

来源:互联网 发布:网络购物数据分析 编辑:程序博客网 时间:2024/05/21 08:37

[plain]
 view plaincopy
  1. Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.  
  2.   
  3. Most interaction with a message loop is through the Handler class.  
  4.   
  5. This is a typical example of the implementation of a Looper thread, using the separation of prepare() and loop() to create an initial Handler to communicate with the Looper.  

类用于为一个线程运行一个消息循环。默认情况下线程没有相关联的消息循环;可以通过在线程里调用looper的prepare()方法创建一个looper,然后就会调用loop()处理消息之道loop被停止。

大多数消息是通过handler来处理。

下面是一个典型的Looper thread的实现,使用分离的准备()和循环()来创建一个Handler与Looper进行通信。

[java] view plaincopy
  1. class LooperThread extends Thread {  
  2.       public Handler mHandler;  
  3.   
  4.       public void run() {  
  5.           Looper.prepare();  
  6.   
  7.           mHandler = new Handler() {  
  8.               public void handleMessage(Message msg) {  
  9.                   // process incoming messages here  
  10.               }  
  11.           };  
  12.   
  13.           Looper.loop();  
  14.       }  
  15.   }  

先看一下类中的变量:

[java] view plaincopy
  1. // sThreadLocal.get() will return null unless you've called prepare().  
  2.     static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();  
  3.   
  4.     final MessageQueue mQueue;  
  5.     final Thread mThread;  
  6.     volatile boolean mRun;  
  7.   
  8.     private Printer mLogging = null;  
  9.     private static Looper mMainLooper = null;  // guarded by Looper.class  

  1. ThreadLocal主要是用于存放looper,如果没有调用prepare()方法的话,使用sThreadLocal的get方法会返回空。具体原因会在后面代码里具体说明。关于ThreadLocal,在这多说两句:ThreadLocal很容易让人望文生义,想当然地认为是一个“本地线程”。其实,ThreadLocal并不是一个Thread,而是Thread的局部变量,也许把它命名为ThreadLocalVariable更容易让人理解一些。
      当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
      从线程的角度看,目标变量就像是线程的本地变量,这也是类名中“Local”所要表达的意思。
  2. 一个MessageQueue,用于存放消息,详情请看:MessageQueue源码解析
  3. 和这个looper相关的线程
  4. looper是否开启,注意他的关键字:volatile:Volatile修饰的成员变量在每次被线程访问时,都强迫从共享内存中重读该成员变量的值( 作为指令关键字,确保本条指令不会因编译器的优化而省略,且要求每次直接读值)。而且,当成员变量发生变化时,强迫线程将变化值回写到共享内存。这样在任何时刻,两个不同的线程总是看到某个成员变量的同一个值。Java语言规范中指出:为了获得最佳速度,允许线程保存共享成员变量的私有拷贝,而且只当线程进入或者离开同步代码块时才与共享成员变量的原始值对比。这样当多个线程同时与某个对象交互时,就必须要注意到要让线程及时的得到共享成员变量的变化。而volatile关键字就是提示VM:对于这个成员变量不能保存它的私有拷贝,而应直接与共享成员变量交互。使用建议:在两个或者更多的线程访问的成员变量上使用volatile当要访问的变量已在synchronized代码块中,或者为常量时,不必使用。由于使用volatile屏蔽掉了VM中必要的代码优化,所以在效率上比较低,因此一定在必要时才使用此关键字
  5. 一个printer类型的mLogging。看下printer:一个用于打印信息的简单接口。
    [java] view plaincopy
    1. Simple interface for printing text, allowing redirection to various targets. Standard implementations are android.util.LogPrinter, android.util.StringBuilderPrinter, and android.util.PrintWriterPrinter.  

  6. 主线程(UI线程)looper。(在UI线程中系统会自动创建looper,其原理会在下面代码中进行解析)         

看完变量,再看构造方法:

[java] view plaincopy
  1. private Looper() {  
  2.         mQueue = new MessageQueue();  
  3.         mRun = true;  
  4.         mThread = Thread.currentThread();  
  5.     }  

初始化变量。                                       


[java] view plaincopy
  1.  /** Initialize the current thread as a looper. 
  2.   * This gives you a chance to create handlers that then reference 
  3.   * this looper, before actually starting the loop. Be sure to call 
  4.   * {@link #loop()} after calling this method, and end it by calling 
  5.   * {@link #quit()}. 
  6.   */  
  7. public static void prepare() {  
  8.     if (sThreadLocal.get() != null) {  
  9.         throw new RuntimeException("Only one Looper may be created per thread");  
  10.     }  
  11.     sThreadLocal.set(new Looper());  
  12. }  
        看一下prepare类,首先它是一个静态类。为当前线程初始化一个looper,在正式启动这个loop的之前,你有机会创建一个handler和这个looper关联。在调用loop方法之前,一定要确认调用prepare方法,在最后结束的时候调用quit方法。如果这个线程已经设过了looper的话就会报错这说明,一个线程只能设一个looper。

[java] view plaincopy
  1. /** 
  2.   * Initialize the current thread as a looper, marking it as an 
  3.   * application's main looper. The main looper for your application 
  4.   * is created by the Android environment, so you should never need 
  5.   * to call this function yourself.  See also: {@link #prepare()} 
  6.   */  
  7.  public static void prepareMainLooper() {  
  8.      prepare();  
  9.      setMainLooper(myLooper());  
  10.      myLooper().mQueue.mQuitAllowed = false;  
  11.  }  

接下来是prepareMainLooper方法,为应用UI线程初始化一个looper,这个主looper是由android环境自动创建,所以不需要你调用这个方法。方法内部调用了prepare方法为线程初始化一个looper。最后那句代码是把queue的允许退出设为false。

然后调用setMainLooper这个方法为mMainLooper赋值

[java] view plaincopy
  1. private synchronized static void setMainLooper(Looper looper) {  
  2.         mMainLooper = looper;  
  3.     }  
而myLooper方法:

[java] view plaincopy
  1. /** 
  2.      * Return the Looper object associated with the current thread.  Returns 
  3.      * null if the calling thread is not associated with a Looper. 
  4.      */  
  5.     public static Looper myLooper() {  
  6.         return sThreadLocal.get();  
  7.     }  

就是为了获取前面prepare方法初始化的looper。这个方法返回与当前线程想关联的Looper实体,如果调用这个方法的线程没有与looper相关联,则返回空。

下面一个方法是获取MainLooper:

[java] view plaincopy
  1. /** Returns the application's main looper, which lives in the main thread of the application. 
  2.     */  
  3.    public synchronized static Looper getMainLooper() {  
  4.        return mMainLooper;  
  5.    }  

返回在主线程里存在的主looper。

下面是本篇代码之重点:loop方法:

[java] view plaincopy
  1. /** 
  2.      * Run the message queue in this thread. Be sure to call 
  3.      * {@link #quit()} to end the loop. 
  4.      */  
  5.     public static void loop() {  
  6.         Looper me = myLooper();//获取当前looper  
  7.         if (me == null) {  
  8.             throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");  
  9.         }//如果为空,则抛异常  
  10.         MessageQueue queue = me.mQueue;//把当前looper的queue赋值给局部变量queue  
  11.           
  12.         // Make sure the identity of this thread is that of the local process,  
  13.         // and keep track of what that identity token actually is.  
  14.         Binder.clearCallingIdentity();//确保当前线程属于当前进程,并且记录真实的token。  
  15.         final long ident = Binder.clearCallingIdentity();  
  16.           
  17.         while (true) {  
  18.             Message msg = queue.next(); // might block有可能会阻塞  
  19.             if (msg != null) {  
  20.                 if (msg.target == null) {  
  21.                     // No target is a magic identifier for the quit message.退出消息的标示就是target为空  
  22.                     return;  
  23.                 }  
  24.   
  25.                 long wallStart = 0;  
  26.                 long threadStart = 0;  
  27.   
  28.                 // This must be in a local variable, in case a UI event sets the logger 一个局部变量,为ui事件设置log记录。  
  29.                 Printer logging = me.mLogging;  
  30.                 if (logging != null) {  
  31.                     logging.println(">>>>> Dispatching to " + msg.target + " " +  
  32.                             msg.callback + ": " + msg.what);  
  33.                     wallStart = SystemClock.currentTimeMicro();  
  34.                     threadStart = SystemClock.currentThreadTimeMicro();  
  35.                 }  
  36.                  //handler处理消息  
  37.                 msg.target.dispatchMessage(msg);  
  38.   
  39.                 if (logging != null) {  
  40.                     long wallTime = SystemClock.currentTimeMicro() - wallStart;  
  41.                     long threadTime = SystemClock.currentThreadTimeMicro() - threadStart;  
  42.   
  43.                     logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);  
  44.                     if (logging instanceof Profiler) {  
  45.                         ((Profiler) logging).profile(msg, wallStart, wallTime,  
  46.                                 threadStart, threadTime);  
  47.                     }  
  48.                 }  
  49.   
  50.                 // Make sure that during the course of dispatching the  
  51.                 // identity of the thread wasn't corrupted.确保调用过程中线程没有被销毁  
  52.                 final long newIdent = Binder.clearCallingIdentity();  
  53.                 if (ident != newIdent) {  
  54.                     Log.wtf(TAG, "Thread identity changed from 0x"  
  55.                             + Long.toHexString(ident) + " to 0x"  
  56.                             + Long.toHexString(newIdent) + " while dispatching to "  
  57.                             + msg.target.getClass().getName() + " "  
  58.                             + msg.callback + " what=" + msg.what);  
  59.                 }  
  60.                 //<span style="font-family: 宋体; font-size: 14px; line-height: 25px; ">处理完成后,调用Message.recycle()将其放入Message Pool中。 </span>  
  61.                 msg.recycle();  
  62.             }  
  63.         }  
  64.     }  

这个方法,主要讲解在注释中。

[java] view plaincopy
  1. /** 
  2.      * Control logging of messages as they are processed by this Looper.  If 
  3.      * enabled, a log message will be written to <var>printer</var>  
  4.      * at the beginning and ending of each message dispatch, identifying the 
  5.      * target Handler and message contents. 
  6.      *  
  7.      * @param printer A Printer object that will receive log messages, or 
  8.      * null to disable message logging. 
  9.      */  
  10.     public void setMessageLogging(Printer printer) {  
  11.         mLogging = printer;  
  12.     }  

设置使用looper处理消息时的log,如果启用,在每条消息分派开始和结束的日志消息将被写入到Printer类,以确定目标Handler和消息内容。

[java] view plaincopy
  1. /** 
  2.     * Return the {@link MessageQueue} object associated with the current 
  3.     * thread.  This must be called from a thread running a Looper, or a 
  4.     * NullPointerException will be thrown. 
  5.     */  
  6.    public static MessageQueue myQueue() {  
  7.        return myLooper().mQueue;  
  8.    }  

返回与当前线程相关联的MessageQueue。当Looper运行时,该方法一定会被调用。

[java] view plaincopy
  1. public void quit() {  
  2.     Message msg = Message.obtain();  
  3.     // NOTE: By enqueueing directly into the message queue, the  
  4.     // message is left with a null target.  This is how we know it is  
  5.     // a quit message.  
  6.     mQueue.enqueueMessage(msg, 0);  
  7. }  

退出方法,往消息队列中加一个空msg。这就是约定的退出消息,在处理该消息时,looper就会退出。

返回当前线程和返回当前Messagequeue:

[java] view plaincopy
  1. /** 
  2.  * Return the Thread associated with this Looper. 
  3.  */  
  4. public Thread getThread() {  
  5.     return mThread;  
  6. }  
  7.   
  8. /** @hide */  
  9. public MessageQueue getQueue() {  
  10.     return mQueue;  
  11. }  

在往后就是打印打印,异常定义的dump方法:

[java] view plaincopy
  1. public void dump(Printer pw, String prefix) {  
  2.         pw = PrefixPrinter.create(pw, prefix);  
  3.         pw.println(this.toString());  
  4.         pw.println("mRun=" + mRun);  
  5.         pw.println("mThread=" + mThread);  
  6.         pw.println("mQueue=" + ((mQueue != null) ? mQueue : "(null"));  
  7.         if (mQueue != null) {  
  8.             synchronized (mQueue) {  
  9.                 long now = SystemClock.uptimeMillis();  
  10.                 Message msg = mQueue.mMessages;  
  11.                 int n = 0;  
  12.                 while (msg != null) {  
  13.                     pw.println("  Message " + n + ": " + msg.toString(now));  
  14.                     n++;  
  15.                     msg = msg.next;  
  16.                 }  
  17.                 pw.println("(Total messages: " + n + ")");  
  18.             }  
  19.         }  
  20.     }  

最后面还有一个有关log的接口:

[java] view plaincopy
  1. /** 
  2.      * @hide 
  3.      */  
  4.     public static interface Profiler {  
  5.         void profile(Message message, long wallStart, long wallTime,  
  6.                 long threadStart, long threadTime);  
  7.     }  


0 0