Handler和消息队列学习

来源:互联网 发布:高中数学讲解视频软件 编辑:程序博客网 时间:2024/05/07 16:52
SDK文档中有以下对Handler的描述
Each Handler instance is associated with a single thread and that thread's message queue.
When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it

翻译:每个Handler实例都和一个简单线程以及该线程的消息队列相关联,当创建一个新Handler时,该Handler跟创建它的线程的线程/消息队列绑定。
那Handler是怎么和创建它的线程以及线程的消息队列绑定的呢。且看下文。

当我们new一个Handler的时候调用了它的构造函数

[java] view plaincopy
  1. public Handler() {  
  2.     ....  
  3.        mLooper = Looper.myLooper();//mLooper 是一个Loop  
  4.        if (mLooper == null) {  
  5.            throw new RuntimeException(  
  6.                "Can't create handler inside thread that has not called Looper.prepare()");  
  7.        }  
  8.        mQueue = mLooper.mQueue;//mQueue是一个MessageQueue,也就是我们要找的消息队列,  
  9.        mCallback = null;//是一个Callback,是Handler的内部接口,  
  10.    }  
    查看Loop的文档:
 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.

Loop类是用来为线程运行消息循环的,线程默认情况下没有与之相关联的消息循环,为了创建消息循环,在运行loop的线程里调用prepare方法,然后调用loop方法来处理消息知道循环结束。
SDK中也给了个使用Loop的实例:

[java] view plaincopy
  1. class LooperThread extends Thread {  
  2.   *      public Handler mHandler;  
  3.   *        
  4.   *      public void run() {  
  5.   *          Looper.prepare();//在线程里调用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.   *  }  
来看看prepare方法:

[java] view plaincopy
  1. public static final void prepare() {  
  2.     if (sThreadLocal.get() != null) {//sThreadLocal为ThreadLocal类,即线程局部变量,含线程自己的独立副本,使线程可以独立地改变自己的副本  
  3.         throw new RuntimeException("Only one Looper may be created per thread");  
  4.     }  
  5.     sThreadLocal.set(new Looper());//把Looper对象放入线程局部变量中,使得Looper()对象与线程关联了起来  
  6. }  
来看看Looper的构造函数,构造函数中创建了消息队列,并记录当前线程,使当前线程与消息队列相关

[java] view plaincopy
  1. private Looper() {  
  2.     mQueue = new MessageQueue();//创建消息队列,  
  3.     mRun = true;  
  4.     mThread = Thread.currentThread();//当前线程  
  5. }  
    在SDk我们给的例子知道,先调用prepare,然后再new Handler实例,然后再调用loop方法,
    在prepare方法中new了一个 Looper(),创建了消息队列并把消息队列和创建它的线程绑定,然后把Looper放入线程局部变量中,使不同的线程都有自己的独立副本,
    然后我们再去实例化Handler类,在Handler的构造函数中调用了Looper.myLooper()获得了Loop,我们看看myLooper()方法

[java] view plaincopy
  1. public static final Looper myLooper() {  
  2.        return (Looper)sThreadLocal.get();  
  3.    }  
    myLooper方法就是从刚才的线程局部变量中拿出和线程相关的Looper,然后把Looper的消息队列都赋给Hanlder的消息队列,这样,
    每个Handler实例都和一个简单线程以及该线程的消息队列相关联,因而实际上,Hanlder保存的消息队列实际上是与之相关的Looper中的消息队列。
    创建Hander的线程和Looper、消息队列的线程也都是同一个线程。我们再来看看Looper.loop()

[java] view plaincopy
  1. public static final void loop() {  
  2.         Looper me = myLooper();//也是获得线程局部变量中的Looper  
  3.         MessageQueue queue = me.mQueue;//线程的消息队列  
  4.         while (true) {//循环  
  5.             Message msg = queue.next(); // might block//线程消息队列是一个链表,含有它的下一条消息  
  6.             //if (!me.mRun) {  
  7.             //    break;  
  8.             //}  
  9.             if (msg != null) {  
  10.                 if (msg.target == null) {//把target设置为null意味着退出消息循环(target为Handler类),以后可以使用这种方式来退出消息循环  
  11.                     // No target is a magic identifier for the quit message.  
  12.                     return;  
  13.                 }  
  14.                 if (me.mLogging!= null) me.mLogging.println(  
  15.                         ">>>>> Dispatching to " + msg.target + " "  
  16.                         + msg.callback + ": " + msg.what  
  17.                         );  
  18.                 msg.target.dispatchMessage(msg);//调用Handler的分发dispatchMessage方法  
  19.                 if (me.mLogging!= null) me.mLogging.println(  
  20.                         "<<<<< Finished to    " + msg.target + " "  
  21.                         + msg.callback);  
  22.                 msg.recycle();  
  23.             }  
  24.         }  
  25.     }  
来看看dispatchMessage

[java] view plaincopy
  1. public void dispatchMessage(Message msg) {  
  2.        if (msg.callback != null) {//消息中的callback为Runnable类,不空时调用run方法  
  3.            handleCallback(msg);  
  4.        } else {  
  5.            if (mCallback != null) {//mCallback为Handler类的内部接口Callback,有handleMessage一个方法,如果不为空的话则执行该Callback的handleMessage方法,该方法由用户去创建  
  6.                if (mCallback.handleMessage(msg)) {  
  7.                    return;  
  8.                }  
  9.            }  
  10.            handleMessage(msg);//如果Message的callback不为空,Handler的Callback不为空才会执行该方法,该方法也是SDK推荐的在创建Handler时必须实现的方法,在该方法中实行所要的操作  
  11.        }  
  12.    }  
由以上分析我们知道,Handler可以3种形式的方法来处理消息,
1、把处理消息放在一个Runnable中,然把Runnable放到Message中,再把Message传给Handler,可以使用Message obtain(Handler h, Runnable callback)方法实现
2、实现Handler的CallBack接口,把处理代码放入CallBack的handleMessage中,然后把该Callback放入Handler中,用Handler的构造器实现Handler(Callback callback);
3、实现Handler的handleMessage方法,一般情况下常用这种方法
到此关于Handler跟创建它的线程的线程/消息队列绑定以及消息队列的处理机制都讲得差不多了。
但是还有一个疑问,我们知道在主线程(UI线程)中也会有自己的消息队列,那么主线程(UI线程)的消息队列是怎么创建的呢,会不会和前边说到的创建情况类似?答案是肯定的。
一般情况下我们把更新UI的程序也写在一个Handler中,用来更新主线程的UI。当我们在UI线程中new一个Handler时,
该Handler就用到了主线程的消息队列,主线程也是该Handler的当前线程,但是在一个Activity中我们并没有看到Looper.prepare()的调用,也没看到Looper.loop()的调用,
我们知道只有在prepare中才会创建跟线程绑定的消息队列,然后用loop来实现消息队列,但是在Activity和它的父类中都没有找到,那么prepare和loop是在哪实现的呢。这时候就用到了ActivityThread类。
我们在启动的Activity中的onCreate方法中加上断点



然后用debug模式打开模拟器,在debug模式下可以看到如下的信息:


在Activity启动的过程中先调用ActivityThread的main方法,

[java] view plaincopy
  1. public static final void main(String[] args) {  
  2.        SamplingProfilerIntegration.start();  
  3.   
  4.        Process.setArgV0("<pre-initialized>");  
  5.   
  6.        Looper.prepareMainLooper();//prepare  
  7.   
  8.        ActivityThread thread = new ActivityThread();  
  9.        thread.attach(false);  
  10.   
  11.        Looper.loop();//loop  
  12.   
  13.        if (Process.supportsProcesses()) {  
  14.            throw new RuntimeException("Main thread loop unexpectedly exited");  
  15.        }  
  16.   
  17.        thread.detach();  
  18.        String name = (thread.mInitialApplication != null)  
  19.            ? thread.mInitialApplication.getPackageName()  
  20.            : "<unknown>";  
  21.        Slog.i(TAG, "Main thread of " + name + " is now exiting");  
因此UI主线程才会有自己的消息队列。
那我们知道在UI主线程中创建Handler时该Handler就会用到主线程的消息队列,如果要想另起线程,开辟新的消息队列应该怎么弄的,SDK给我们提供了一个HandlerThread类,只要如下调用

[java] view plaincopy
  1. HandlerThread handlerThread = new HandlerThread("handler_thread");  
  2.   //在使用HandlerThread的getLooper()方法之前,必须先调用该类的//start();  
  3.   handlerThread.start();  
  4.   MyHandler myHandler = new MyHandler(handlerThread.getLooper());//传入新的Loop到Handler里边  
HandlerThread继承了Thread方法,因而调用start方法会启动一个新的线程,我们来看看run中的实现

[java] view plaincopy
  1. public void run() {  
  2.     mTid = Process.myTid();  
  3.     Looper.prepare();//  
  4.     synchronized (this) {  
  5.         mLooper = Looper.myLooper();  
  6.         notifyAll();  
  7.     }  
  8.     Process.setThreadPriority(mPriority);  
  9.     onLooperPrepared();  
  10.     Looper.loop();//  
  11.     mTid = -1;  
  12. }  
在run中用到了prepare --' loop 因而可以在新的线程中创建新的消息队列。
完~
0 0
原创粉丝点击