Handler和消息队列学习

来源:互联网 发布:java可以做爬虫吗 编辑:程序博客网 时间:2024/05/29 09:15
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的时候调用了它的构造函数

 public Handler() {....        mLooper = Looper.myLooper();//mLooper 是一个Loop        if (mLooper == null) {            throw new RuntimeException(                "Can't create handler inside thread that has not called Looper.prepare()");        }        mQueue = mLooper.mQueue;//mQueue是一个MessageQueue,也就是我们要找的消息队列,        mCallback = null;//是一个Callback,是Handler的内部接口,    }
    查看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的实例:

class LooperThread extends Thread {  *      public Handler mHandler;  *        *      public void run() {  *          Looper.prepare();//在线程里调用prepare方法  *            *          mHandler = new Handler() {  *              public void handleMessage(Message msg) {  *                  // process incoming messages here  *              }  *          };  *            *          Looper.loop();//循环处理消息  *      }  *  }
来看看prepare方法:

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

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

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

public static final void loop() {        Looper me = myLooper();//也是获得线程局部变量中的Looper        MessageQueue queue = me.mQueue;//线程的消息队列        while (true) {//循环            Message msg = queue.next(); // might block//线程消息队列是一个链表,含有它的下一条消息            //if (!me.mRun) {            //    break;            //}            if (msg != null) {                if (msg.target == null) {//把target设置为null意味着退出消息循环(target为Handler类),以后可以使用这种方式来退出消息循环                    // No target is a magic identifier for the quit message.                    return;                }                if (me.mLogging!= null) me.mLogging.println(                        ">>>>> Dispatching to " + msg.target + " "                        + msg.callback + ": " + msg.what                        );                msg.target.dispatchMessage(msg);//调用Handler的分发dispatchMessage方法                if (me.mLogging!= null) me.mLogging.println(                        "<<<<< Finished to    " + msg.target + " "                        + msg.callback);                msg.recycle();            }        }    }
来看看dispatchMessage

 public void dispatchMessage(Message msg) {        if (msg.callback != null) {//消息中的callback为Runnable类,不空时调用run方法            handleCallback(msg);        } else {            if (mCallback != null) {//mCallback为Handler类的内部接口Callback,有handleMessage一个方法,如果不为空的话则执行该Callback的handleMessage方法,该方法由用户去创建                if (mCallback.handleMessage(msg)) {                    return;                }            }            handleMessage(msg);//如果Message的callback不为空,Handler的Callback不为空才会执行该方法,该方法也是SDK推荐的在创建Handler时必须实现的方法,在该方法中实行所要的操作        }    }
由以上分析我们知道,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方法,

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

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

    public void run() {        mTid = Process.myTid();        Looper.prepare();//        synchronized (this) {            mLooper = Looper.myLooper();            notifyAll();        }        Process.setThreadPriority(mPriority);        onLooperPrepared();        Looper.loop();//        mTid = -1;    }
在run中用到了prepare --' loop 因而可以在新的线程中创建新的消息队列。
完~








原创粉丝点击