Looper.loop() android线程中的消息循环

Looper用于封装了android线程中的消息循环,默认状况下一个线程是不存在消息循环(message loop)的,须要调用Looper.prepare()来给线程建立一个消息循环,调用Looper.loop()来使消息循环起做用,从消息队列里取消息,处理消息。
注:写在Looper.loop()以后的代码不会被当即执行,当调用后mHandler.getLooper().quit()后,loop才会停止,其后的代码才能得以运行。Looper对象经过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。
如下是Android API中的一个典型的Looper thread实现:
//Handler不带参数的默认构造函数:new Handler(),其实是经过Looper.myLooper()来获取当前线程中的消息循环, //而默认状况下,线程是没有消息循环的,因此要调用 Looper.prepare()来给线程建立消息循环,而后再经过,Looper.loop()来使消息循环起做用。
class LooperThread extends Thread java

         {android

                  public Handler mHandler; 函数

                  public void run() oop

                          {ui

                                  Looper.prepare();spa

                                  mHandler = new Handler() .net

                                          {线程

                                                public void handleMessage(Message msg)code

                                                              { 对象

                                                                    // process incoming messages here

                                                              }

                                          };

                                  Looper.loop();

            }

另,Activity的MainUI线程默认是有消息队列的。因此在Activity中新建Handler时,不须要先调用Looper.prepare()。

何时使用Looper.prepare()

当你的线程想拥有本身的MessageQueue的时候先Looper.prepare(),而后Looper.loop();
参照源码:

 

  1. public static final void prepare() {     
  2.        if (sThreadLocal.get() != null) {     
  3.            throw new RuntimeException("Only one Looper may be created per thread");     
  4.        }     
  5.        sThreadLocal.set(new Looper());     
  6.    }     
public static final void prepare() {   
       if (sThreadLocal.get() != null) {   
           throw new RuntimeException("Only one Looper may be created per thread");   
       }   
       sThreadLocal.set(new Looper());   
   }   

 

 
这段代码就是经过ThreadLocal来产生一个Looper对象作为线程局部变量,而后调用Looper.loop()则是取出Looper对象中的MessageQueue进行消息循环了,这样造成了这个线程的消息队列。 通常状况下只会有主线程会调用prepare方法(ActivityThread的main函数)。
 

使线程拥有本身的消息列队,主线程拥有本身的消息列队,通常线程建立时没有本身的消息列队,消息处理时就在主线程中完成,若是线程中使用Looper.prepare()和Looper.loop()建立了消息队列就可让消息处理在该线程中完成

相关文章
相关标签/搜索