Android消息处理机制详解

首先需要介绍几个非常重要的角色:Looper、Handler、HandlerThread、MessageQueue、Message

Looper帮助一个线程维护一个消息队列,每一个线程都可以拥有一个Looper对象。
Handler负责把消息放入线程的消息队列中以及分发消息。
HandlerThread本身是一个Thread,并且内部封装了一个Looper对象,所以不用我们去关心Looper的创建和释放问题。
Message本身是一个Parcelable对象,MessageQueue用来存储一些待分发的Message,内部实现了一个Message链表的结构。
在一个子线程中创建Handler时,必须初始化该线程的Looper对象,因为普通的Thread默认是没有消息队列的。程序启动的时候,系统会为主线程(UI线程)创建一个Looper对象和消息队列,我们可以通过Looper.getMainLooper()获得。如果不使用HandlerThread,则通常我们在子线程中创建一个Handler的代码如下所示:


class MyThread extends Thread {      
    public Handler mHandler;     
 
    public void run() {      
       Looper.prepare();          
 
       mHandler = new Handler() {       
 
       public void handleMessage(Message msg) {          
 
        /* 处理接收到的消息 */
 
       }     
 
     };               
     Looper.loop(); 
 
   }
}
 可以使用HandlerThread替代上面的方式,代码如下:


[font=Courier New]class[/font] MyHandler extends Handler {         public MyHandler(Looper looper) {
            super(looper);
        }
 
 
        public void handleMessage(Message msg) {
            /** 处理接收到的消息*/
 
        }
    }
 
 
   class UpdateRunnable implements Runnable {
 
 
        public void run() {
            Message msg = mHandler.obtainMessage();
            msg.what = 10000;
            msg.sendToTarget();
        }
 
 
    }
 
 
//在需要调用的地方,加入下面代码即可
HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
handlerThread.start();
mHandler = new MyHandler(handlerThread.getLooper());
//add to MessageQueue
mHandler.post(new UpdateRunnable());
 

这两种方式原理是一样的,HandlerThread在run方法中也调用了Looper.prepare()和Looper.loop()方法。
那这两个方法做了些什么呢?下面根据sdk源码来分析。

 

public static void prepare() {     prepare(true); }

 

private static void prepare(boolean quitAllowed) {  

   if (sThreadLocal.get() != null) {

        throw new RuntimeException("Only one Looper may be created per thread");     }

    sThreadLocal.set(new Looper(quitAllowed));

}  

可以看到,调用Looper.prepare()时,为当前线程创建了一个Looper对象,继续跟踪,看创建Looper对象的时候又做了些什么呢?


private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mRun = true;
    mThread = Thread.currentThread();
}
 为当前绑定的线程创建了一个消息队列,下面继续看Looper.loop()内部干了些啥呢?

public static void loop() {    

final Looper me = myLooper();

    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 (;;) {

        Message msg = queue.next(); // might block        

        if (msg == null) {             // No message indicates that the message queue is quitting.         

       return;        

       }

        // This must be in a local variable, in case a UI event sets the logger       

     Printer logging = me.mLogging;    

     if (logging != null) {          

       logging.println(">>>>> Dispatching to " + msg.target + " " +msg.callback + ": " + msg.what);      

       }

        msg.target.dispatchMessage(msg);

        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.recycle();    

}

}  

从源码可以看出,在一个无限for循环中遍历消息队列,然后调用Handler进行消息分发处理,分发之后调用recycle()把Message对象回收到Message Pool中(最大值为50个,若消息池中已经有50个Message,则丢弃不保存),实现Message对象的复用,调用handler.obtainMessage()时就是从消息池取得Message对象。当消息队列返回null时就退出循环。

调用next函数时,也是执行一个无限for循环,直接获取消息链表指向的下一个节点,判断该消息指定的执行时间是否已到,若已到则返回Message对象,若没有满足条件的Message,则继续等待直到线程结束,具体方法可以查询MessageQueue.java源码。

现在Looper对象和消息队列已经创建好了,看看Handler是怎么分发消息的。


public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}
 handler的处理比较简单,先判断Message中有没有指定的callback对象(Runnable),有的话就调用callback的run方法,没有则调用我们自己创建Handler对象时实现的handleMessage(Message msg)方法,就这样实现了消息的分发。还有一个疑问没有解决,就是handler如何把消息添加到消息队列呢?继续跟踪Handler的sendMessage函数。


public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
 
 
public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
 
 
public boolean sendMessageAtTime(Message msg, long uptimeMillis)
    {
        boolean sent = false;
        MessageQueue queue = mQueue;
        if (queue != null) {
            msg.target = this;
            sent = queue.enqueueMessage(msg, uptimeMillis);
        }
        else {
            RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
        }
        return sent;
    }
 enqueueMessage这个函数就是我们要找的,它负责把Message对象添加到了MessageQueue管理的Message链表里。

原文链接:http://codingnow.cn/android/582.html

 

 

posted @ 2012-09-20 13:57  卡诺图  阅读(129)  评论(0编辑  收藏  举报